簡體   English   中英

如何將原型添加到 object

[英]how to add a prototype to an object

以下 function 產生錯誤“ scoreCounter is not defined”,此時應將其定義為Darts的原型。

function Darts() {
    this.Score = 0
    this.x = 1
    this.y = 1
} 

Darts.prototype.scoreCounter = function(x,y) {
(unnecessary code for this quesiton)
}
const test = new Darts()


console.log(test.isPrototypeOf(scoreCounter))

如何修復此錯誤(正確添加原型)

scoreCounter預計將作為 output 成為test原型的一部分

您只定義Darts.prototype.scoreCounter ,而不是名稱為scoreCounter的變量; 因此, scoreCounter方法僅在Darts原型或Darts function 實例上可見,即new Darts().scoreCounter 要查找是否已在函數的原型上定義方法,可以根據情況使用Object#hasOwnPropertyin運算符

 function Darts() { this.Score = 0 this.x = 1 this.y = 1 } Darts.prototype.scoreCounter = function(x,y) { //(unnecessary code for this quesiton) } const test = new Darts() console.log(test.hasOwnProperty("scoreCounter"));//false; it's a prototype property console.log("scoreCounter" in test); //true; inherited property found on the prototype chain console.log(Darts.prototype.hasOwnProperty("scoreCounter"));//true

在 console.log 語句中,您正在測試“scoreCounter”,但“scoreCounter”不是全局工作區中的全局變量。

嘗試這個:

console.log(Darts.prototype.isPrototypeOf(test))

^^^ 我們只需要檢查'test'中的原型是否來自原型鏈中更高的'Darts'。 這將包括搜索中“飛鏢”內的任何原型。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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