之前推荐的这篇原型链的哲学思想.
该文中有这么一段话.
在JavaScript中,每个对象都拥有一个原型对象,而指向该原型对象的内部指针则是__proto__,通过它可以从中继承原型对象的属性,原型是JavaScript中的基因链接,有了这个,才能知道这个对象的祖祖辈辈。从对象中的__proto__可以访问到他所继承的原型对象。
再贴一段验证的代码.
var a = new Array();
console.log( a.__proto__ === Array.prototype ); // true 即Array.prototype是a的原型对象
console.log( a.__proto__.__proto__ === Object.prototype ); // true
console.log( a.__proto__.__proto__.__proto__ === null ); // true
以上是支持作者观点的。
我再补上一段验证代码:
// Array.isPrototypeOf(a) 验证Array是不是a实例的原型,结果是false.
后来醒悟过来,犯了个错误. a.prototype 指的是 Array.prototype
console.log(Array.isPrototypeOf(a));//false
console.log(a);//[]
console.log(Array.prototype.isPrototypeOf(a)); // true 这就对了
上面是通过new + 构造函数方式实现继承,那对象字面量方式实现继承是怎么样的
var C = {
c : 1
}
var D = Object.create(C);
D.d = 4;
console.log(D.constructor); //function Object() { } Object构造函数
console.log(D.constructor.prototype ); //Object {} Object对象
console.log(C.isPrototypeOf(D)); // true
console.log(D.__proto__ === C); // true
总结下: Object.create()创建的对象的constructor属性指向Object构造函数,其constructor.prototype指向Obejct对象.