javascript - 如何将原型添加到对象
问题描述
以下函数产生错误“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
原型的一部分作为输出
解决方案
您只定义Darts.prototype.scoreCounter
了 ; 而不是名称为scoreCounter
;的变量。因此,该scoreCounter
方法仅Darts
在函数的原型或实例上可见Darts
,即new Darts().scoreCounter
。要查找是否已在函数的原型上定义了方法,您可以使用Object#hasOwnProperty
或in
运算符,具体取决于具体情况。
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
推荐阅读
- user-interface - 我被困在我的 GUI [wxpython] 中使用绝对定位
- javascript - 为什么 DIV 认为 Element 是字符串?
- json - Bash 创建 JSON 文件清单
- view - Windows 10 快速访问 将默认视图更改为详细信息
- css - 到底为什么底部 0 在这里不起作用?
- cucumber - 对黄瓜使用 SoftAssertion
- java - 当我用 sbt 运行 play 框架时出现一些错误
- html - 无法使用 jspdf 以角度打印包含 pdf 转换中的输入字段的 Html 表
- java - 验证 pom.xml 是否符合标准
- r - 使用 curl 包将 cURL POST 翻译成 R