[英]How does JavaScript's prototypal Inheritance work?
我想知道 JavaScript 的原型繼承是如何工作的。當我們使用 new 關鍵字創建對象時,對象的__proto__
設置為Constructor_Function.prototype
。
但我不明白為什么我會得到這個輸出。
我的代碼:
function SimpleFunction(){}
let obj = new SimpleFunction();
console.dir(obj);
輸出 :
SimpleFunction {}
[[Prototype]]: Object
constructor: ƒ SimpleFunction()
[[Prototype]]: Object
constructor: ƒ Object()
hasOwnProperty: ƒ hasOwnProperty()
isPrototypeOf: ƒ isPrototypeOf()
propertyIsEnumerable: ƒ propertyIsEnumerable()
toLocaleString: ƒ toLocaleString()
toString: ƒ toString()
valueOf: ƒ valueOf()
__defineGetter__: ƒ __defineGetter__()
__defineSetter__: ƒ __defineSetter__()
__lookupGetter__: ƒ __lookupGetter__()
__lookupSetter__: ƒ __lookupSetter__()
__proto__: Object
constructor: ƒ SimpleFunction()
[[Prototype]]: Object
constructor: ƒ Object()
hasOwnProperty: ƒ hasOwnProperty()
isPrototypeOf: ƒ isPrototypeOf()
propertyIsEnumerable: ƒ propertyIsEnumerable()
toLocaleString: ƒ toLocaleString()
toString: ƒ toString()
valueOf: ƒ valueOf()
__defineGetter__: ƒ __defineGetter__()
__defineSetter__: ƒ __defineSetter__()
__lookupGetter__: ƒ __lookupGetter__()
__lookupSetter__: ƒ __lookupSetter__()
__proto__: Object
constructor: ƒ Object()
hasOwnProperty: ƒ hasOwnProperty()
isPrototypeOf: ƒ isPrototypeOf()
propertyIsEnumerable: ƒ propertyIsEnumerable()
toLocaleString: ƒ toLocaleString()
toString: ƒ toString()
valueOf: ƒ valueOf()
__defineGetter__: ƒ __defineGetter__()
__defineSetter__: ƒ __defineSetter__()
__lookupGetter__: ƒ __lookupGetter__()
__lookupSetter__: ƒ __lookupSetter__()
__proto__: null
get __proto__: ƒ __proto__()
set __proto__: ƒ __proto__()
get __proto__: ƒ __proto__()
set __proto__: ƒ __proto__()
get __proto__: ƒ __proto__()
set __proto__: ƒ __proto__()
當我嘗試這個時:
obj.__proto__.__proto__.__proto__;
我有 :
null
所以我不明白為什么輸出中有超過三個原型對象。
所以我不明白為什么輸出中有超過三個原型對象。
這是因為SimpleFunction()
構造函數是派生源對象( 函數也是具有原型的對象)。 由於SimpleFunction()
是用戶定義的,因此它必須像所有其他對象一樣從 Object 對象繼承。 因此,您擁有函數對象及其原型 Object 對象,然后您擁有從構造函數派生的obj
及其自己的 Object 對象原型。
不,[[Prototype]] 和__proto__
不是一回事。 如果您查看日志,您將看到名為__proto__
setter 和 getter。 所以__proto__
實際上是存取器屬性[[原型]],而[[原型]]反映了實際的對象,它是原型。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.