每个构造函数都有一个原型对象,
原型对象都包含一个指向构造函数的指针,
实例都包含一个指向原型对象的内部指针。
每个构造函数都有一个原型对象
function Person(name, age, gender) {
this.name = name;
this.age = age;
this.gender = gender;
}
console.log(Person.prototype)
结果:
每个构造函数本身都是一个对象,它有一个属性叫做prototype,它是一个对象
原型对象都包含一个指向构造函数的指针
这个指针(属性)叫做constructor 指向构造函数本身
实例都包含一个指向原型对象的内部指针
function Person(name, age, gender) {
this.name = name;
this.age = age;
this.gender = gender;
}
var person = new Person("小明","7",'4')
console.log(person)
结果:
这个指向原型对象的内部指针叫做__proto__
function Person(name, age, gender) {
this.name = name;
this.age = age;
this.gender = gender;
}
var person = new Person("小明","7",'4')
console.log(person.__proto__===Person.prototype) //true
通过原型可以实现继承
当查找一个对象的属性时,JavaScript 会向上遍历原型链,直到找到给定名称的属性为止,到查找到达原型链的顶部(也就是 Object.prototype),如果仍然没有找到指定的属性,就会返回 undefined。
function Person(name, age, gender) {
this.name = name;
this.age = age;
this.gender = gender;
}
Person.prototype.x = "10"
Object.n = "20"
var person = new Person("小明","7",'4')
console.log(person.x) //10
console.log(person.n) //20
console.log(person.m) //undefined