簡體   English   中英

對JavaScript中的原型感到困惑

[英]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 yy將在創建的對象上設置new yprototype屬性。 因此,如果您執行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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM