目录
原型
每一个构造函数都有一个属性: 原型 / 原型对象
function Student(name,age,sex){
this.name = name;
this.age = age;
this.sex = sex;
}
Student.prototype.sayHi = function () {
console.log('输出一下名字,名字是:',this.name)
}
// 通过Student构造函数,创建的对象,可以访问Student.prototype中的成员
var s1 = new Student('lilei',18,'男')
var s2 = new Student('hmm',18,'女')
console.log(s1.sayHi()); // 输出结果--输出一下名字,名字是:lilei
console.log(s2.sayHi()); // 输出结果--输出一下名字,名字是:hmm
console.log(s1.sayHi===s2.sayHi) //true
构造函数的对象可以访问原型对象中的所有成员;
prototype是一个对象。 通过原型对象增加一些成员,通过构造函数创造的所有对象都可以访问原型对象中增加的这些成员;
constructor 的概念与用法
function Student(name,age,sex){
this.name = name;
this.age = age;
this.sex = sex;
}
Student.prototype.sayHi = function () {
console.log('输出一下名字,名字是:',this.name)
}
// 通过Student构造函数,创建的对象,可以访问Student.prototype中的成员
var s1 = new Student('lilei',18,'男')
var s2 = new Student('hmm',18,'女')
// construtor 作用 记录了创建该对象的构造函数
console.log(s1.constructor) // function Student(name,age,sex){
// this.name = name;
// this.age = age;
// this.sex = sex;
// }
console.log(s1.constructor === Student) // true
var arr = []
console.log(arr.constructor === Array) // true
在原型对象中有一个属性 constructor 构造函数 作用:记录了创建该对象的构造函数
constructor 指向了原型对象所在的函数;
原型链
原型链的意义:属性查找或成员查找的规则,如果在本身找不到了会去对应的链上查找
每个对象都有一个__proto__
,它指向它的prototype
原型对象,而prototype
原型对象又具有一个自己的prototype
原型对象,就这样层层往上直到一个对象的原型prototype
为null
这个查询的路径就是原型链