[英]Confused about prototype in javascript
var y=function(){
return new y.prototype.greeting();
}
y.prototype={
greeting:function(){
alert("hello world");
}
}
new y();
上面的代碼將發出警報(“ hello world”);
但是如果我刪除.prototype
並更改該行以return new y.greeting();
將會發生錯誤:
未定義不是函數
var y=function(){
return new y.greeting();
}
y.prototype={
greeting:function(){
alert("hello world");
}
}
new y();
為什么我不能在沒有prototype
情況下調用greeting
方法?
非常感謝
y
是一個函數,其中的[[Prototype]]
是Function
因此,當您要求解釋器查詢y.greeting
時,它首先查看y
本身,然后檢查Function.prototype
,然后檢查Object.prototype
。
創建 new y
的y
將在創建的對象上設置new y
的prototype
屬性。 因此,如果您執行new (new y()).greetings()
,則將收到alert
。
另一種考慮方式是構造函數的prototype
屬性是將通過調用new constructor
創建的任何子對象的prototype
。 構造函數的實際內部[[Prototype]]
將始終基於構造函數的任何內容 。
您可以在下面的示例中看到這一點。 Object.getPrototypeOf
將返回內部的[[Prototype]]
屬性,因此我們可以看到實際發生的情況:
> var test = function() {}
> Object.getPrototypeOf(test)
function Empty() {}
// Setting the prototype property
// does not change the [[Prototype]] of test
> test.prototype = {x: 1}
> Object.getPrototypeOf(test)
function Empty() {}
// But it *does* change the prototype of
// objects *created by* test.
> var x = new test
> Object.getPrototypeOf(x)
Object {x: 1}
return new y.greeting();
嘗試訪問y真正不存在的屬性(函數)。 這就是為什么它會引發錯誤“未定義的不是函數”的原因,因為y的屬性包含一個包含函數的變量。 就像三層樓一樣,您不能從二樓到一樓而不要一樓。 一種等級制度。 得到它了?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.