如果您尝试打印常规对象的__proto__
属性,例如{}.__proto__
或foo.__proto__
,则会获得[object object]
;这个[object object]
是另一个对象的原型。但是,如果您尝试打印出任何函数的__proto__
属性,它会为您提供function () { [native code] }
。这是为什么 ?它不应该返回Function
继承的对象的原型,它应该是一个对象而不是另一个函数(如function(){native code]}
)?一个函数的__proto__
怎么可能是另一个函数而不是一个对象,就像其他原型一样?
*我知道应该使用Object.getPrototypeOf(obj)代替 proto ,但我之所以使用它,因为它更短。
如果有人向我解释了上述情况,我将不胜感激。如果您对我的问题有任何疑惑,请在评论中提出而不是低估。
答案 0 :(得分:1)
原因
Function.prototype.toString()
将返回
"function (){ [native code] }"
Function.prototype是一个对象,但是当你打印它时,它被类型化为一个字符串,并且当原型实现函数的行为时:
function(){}.toString()
即使它不是,也会打印成功能。
function(){}
.__proto__ // Function.prototype
.__proto__ // Object.prototype
.toString() // "[Object object]
也许更容易想象:
class Human {
toString(){
return "Im a Human";
}
}
console.log(
(new Human).__proto__
);
//the Human.prototype tells you that it is a Human, however its just a class.
答案 1 :(得分:0)
在JavaScript中,使用var o = new f()
调用构造函数会创建一个新对象,并且
将o.__proto__
设置为f.Prototype
。与:相同:
new Array().__proto__ == Array.prototype // true
new Number().__proto__ == Number.prototype // true
或:
[].__proto__ == Array.prototype // true
(5).__proto__ == Number.prototype // true
Function
是构造函数,因此使用new Function()
创建函数会将其原型设置为Function.prototype
:
new Function().__proto__ === Function.prototype // true
或:
(function() {}).__proto__ == Function.prototype // true
所有函数都有相同的原型,包括构造函数。所以:
Function.__proto__ == Function.prototype // true
Array.__proto__ == Function.prototype // true
Number.__proto__ == Function.prototype // true
Function.prototype
定义了所有函数继承的函数的默认行为,包括调用它的能力,因此它本身就是一个函数:
Function.prototype() // undefined
(new Function())() // undefined