我的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
用更好的命令替换,该命令将在第一部分返回“ black”,在第二部分返回“ white”。
谢谢!
首先,您的代码中有一个错字
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
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句