我试图回过头来更好地了解原型继承。我了解实例的__proto__
属性指向构造函数的prototype
对象,但构造函数的__proto__
属性指向什么?
我假设构造函数本身就是Function的一个实例,它会指向Function构造函数的prototype
对象,但是下面显示它是一个空函数。
var Example = function(){
this.attribute = 'example';
}
var exampleInstance = new Example();
exampleInstance.__proto__ === Example.prototype // true
Example.__proto__ // function() {}
[编辑] Ovidiu Dolha现在已经证实了我的理解,所以这可能会对某人有所帮助。
答案 0 :(得分:3)
Example.__proto__
与Function.prototype
相同,就像exampleInstance.__proto__
与Example.prototype
相同
这是因为Example
是函数的一个实例。
一切都将最终到达Object.prototype
,这是原型继承的根源。
请注意,如果可能,您应该避免使用__proto__
,因为它被视为已弃用。而是使用Object.getPrototypeOf()
答案 1 :(得分:0)
它是一个原型链,一直到最后它找到“对象”作为根。
ECMAScript 5.1规范如下所示:
在15.3.4函数原型对象的属性中:
The value of the [[Prototype]] internal property of the Function prototype object is the standard built-in Object prototype object
在15.2.4对象原型对象的属性
中The value of the [[Prototype]] internal property of the Object prototype object is null
在您的控制台中尝试此操作。
console.log(exampleInstance);
Example
attribute
:
"example"
__proto__
:
Object
constructor
:
()
__proto__
:
Object
__defineGetter__
:
__defineGetter__()
__defineSetter__
:
__defineSetter__()
__lookupGetter__
:
__lookupGetter__()
__lookupSetter__
:
__lookupSetter__()
constructor
:
Object()
hasOwnProperty
:
hasOwnProperty()
isPrototypeOf
:
isPrototypeOf()
propertyIsEnumerable
:
propertyIsEnumerable()
toLocaleString
:
toLocaleString()
toString
:
toString()
valueOf
:
valueOf()
get __proto__
:
__proto__()
set __proto__
:
__proto__()