// js 会给每个创建的对象设置一个原型,指向它的原型对象
// var arr=[1,2,3];
/**
* arr对象 其原型对象就是Array,因此js中存在着原型链,arr ----> Array.prototype ----> Object.prototype ----> null
* 由于js定义了Array.prototype中定义了sort(),indexof()等方法,因此你可以在所有的Array对象上直接调用这些方法。所以可以arr.sort();
* 在js中函数也是对象。因此函数也有自己的原型链
*/
function student () {
console.log('测试')
}
// student->Function.prototype->Object.prototype->null,js 创建对象主要由以下两种方法
var lhl = {
name: 'lhl',
age: 23,
hello: function () {
console.log(`${this.name} 是 ${this.age} 岁 `)
}
}
lhl.hello()
// 方法二 通过new 关键字来创建
function Student (name) {
this.name = name
this.hello = function () {
console.log(`我是${this.name}`)
}
};
var lhl = new Student('lhl1')
var lhl2 = new Student('lhl2')
lhl.hello()
lhl2.hello()
// 这里大家会发现,我们每次去重新创建一个学生对象,都会去创建一个hello方法,虽然代码都是一样的,但他们确实两个不同的函数
// 其实这么多对象只需要共享一个hello函数即可,因此根据对象查找原则,我们将hello方法放在Student对象上,便可以实现共享
Student.prototype.hello = function () {
console.log(`我是${this.name}`)
}
// 此外用new创建的对象,还从其原型对象上获得了一个constructor 属性,它门指向Student对象本身
console.log(lhl.constructor === Student.prototype.constructor) // true
console.log(Student.prototype.constructor === Student)// true
console.log(Object.getPrototypeOf(lhl) === Student.prototype) // true
console.log(lhl instanceof Student) // true
// 下面的一个例子是在廖雪峰老师的教程中看到的一个写法,个人感觉很好,特此记录。
function Teacher (props) {
this.name = props.name || 'no-name'
this.age = props.age || 23
}
Teacher.prototype.hello = function () {
console.log(`${this.name}是${this.age}岁!`)
}
function createTeacher (props) {
return new Teacher(props || {})
}
var lhl3 = createTeacher({name: 'lhl'})
lhl3.hello()
2018-11-18 js 面向对象
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
推荐阅读更多精彩内容
- JS中ES6对象与ES5对象的差别 ES6对象与ES5对象的差别 2018 7/16晴-小雨 微风 温度 12-2...
- HTML 学习笔记 May 11,2017 构造函数、成员函数详解、object类、闭包、成员函数再说明、聪明的猪...
- HTML 学习笔记 May 10,2017 js函数调用过程内存分析、js函数细节、js一维数组细节、二维数组转置...
- 前两天看完了 js 面向对象精要, 有所收获, 因此趁热打铁做一下记录. 这本书很薄, 只用了两天午休的时间就看完...