美文网首页
深入之原型与原型链

深入之原型与原型链

作者: 明里人 | 来源:发表于2019-07-13 16:40 被阅读0次
构造函数创建对象
function Person() {
  
}
var person = new Person();
person.name = 'cyl';
console.log(person.name);  // cyl
prototype

每个函数都有一个prototype 属性( 只有函数才会有该属性 ),例如:

function Person() {
}
Person.prototype.name = 'cyl';
var person1 = new Person();
var person2 = new Person();
console.log(person1.name);  // cyl
console.log(person2.name):  // cyl

函数的 prototype 属性指向了一个对象,这个对象是调用该构造函数而创建的实例对象的原型,也就是person1、person2的原型。

__ proto __

每个JavaScript对象(除null)都具有一个属性,叫proto,这个属性会指向构造函数的原型

function Person(){
}
var person = new Person();
console.log(person.__proto__ === Person.prototype);  // true
constructor

每个原型都有一个constructor 属性指向关联的构造函数

function Person(){

}
var person = new Person();
console.log(Person === person.constructor);  // true  从原型继承过来的constructor
console.log(Person === Person.prototype.constructor);  // true

综合得出:

function Person (){

}
var person = new Person();
console.log(person.__proto__ === Person.prototype);  // true
console.log(Person.prototype.constructor === Person);  // true
// ES5 方法 获取对象原型
console.log(Object.getPrototypeOf(person) === Person.prototype);  // true
原型的原型

实例原型的原型指向Object.prototype

function Person() {

}
let person = new Person();
console.log(person.__proto__.__proto__ === Person.prototype.__proto__);  // true
console.log(person.__proto__.__proto__ === Object.prototype);  // true
console.log(Person.prototype.__proto__ === Object.prototype);  // true
原型链

那 Object.prototype 的原型呢?

console.log(Object.prototype.__proto__ === null);  // true

所以 Object.prototype.proto的值为 null,跟 Object.prototype 没有原型是一个意思 。

prototype5.png

相关文章

网友评论

      本文标题:深入之原型与原型链

      本文链接:https://www.haomeiwen.com/subject/cvhmkctx.html