首页 > 解决方案 > 如何将原型添加到对象

问题描述

以下函数产生错误“scoreCounter未定义”,此时应将其定义为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预计将成为test原型的一部分作为输出

标签: javascriptoop

解决方案


您只定义Darts.prototype.scoreCounter了 ; 而不是名称为scoreCounter;的变量。因此,该scoreCounter方法仅Darts在函数的原型或实例上可见Darts,即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


推荐阅读