如何在构造函数中获得构造函数'
How to get the constructor's parent inside the constructor function (JS)
本文关键字:构造函数 更新时间:2023-09-26
我有一个有点复杂的JS对象结构:
var Players = {};
Players.Player = function (color) {
this.color = color; //the color can be either black or white
Players[color] = this;
}
Players.Player.prototpe.Piece = function () {
return this.parent.color //of course, this is not valid
}
new Players.Player("black");
new Players.Player("white");
new Players["black"].Piece(); //here I want to get "black"
new Players["white"].Piece(); //here I want to get "white"
我希望我已经很好地描述了我的问题。我希望能够返回构造函数父部分的颜色,这意味着用更好的命令替换this.parent.color
,该命令将在第一个部分返回"黑色",在第二个部分返回"白色"。
谢谢!
首先你的代码有一个错别字
Players.Player.prototpe.Piece
应为Players.Player.prototype.Piece
如果您使用的是像chrome这样的浏览器,您可以很容易地看到并通过启动开发控制台来修复这些错误。参见如何在chrome中调试
现在继续讨论返回颜色的实际问题,您必须修改代码
从return this.parent.color
到return this.color
,这应该解决问题。
this是javascript中的关键字,可以根据执行函数的上下文正确识别对象实例。
Players.Player.prototype.Piece = function () {
return this.color //this is now valid
}
演示相关文章:
- ES6构造函数返回基类的实例
- 使用Google Visualization动态调用构造函数
- javascript中对象构造函数中的var属性与this.properties
- 理解typescript中的构造函数接口
- 为什么构造函数不是构造函数
- 如果在构造函数中有“返回”,则在 JavaScript 中的新运算符中做了什么
- 拦截对构造函数的调用
- 使用闭包共享构造函数参数
- 文本表示法VS.构造函数,用于在JavaScript中创建对象
- 从js引擎的角度来看闭包和构造函数是如何工作的
- 如何使用此从对象访问构造函数
- Javascript:为什么是构造函数's __proto__属性Empty(){}
- 当一个重要的构造函数参数丢失时应该发生什么
- Chrome Javascript日期构造函数错误
- 如何使用构造函数's的输出,以便将值插入到对象中
- 为什么在调用父构造函数时在[]中发送数据
- 构造函数函数闭包变量
- ES6类是否与构造函数相同
- 构造函数中的事件处理程序与构造函数外的事件处理函数的行为不同
- 如果在构造函数内部为else,则Javascript是可选的