如何在构造函数中获得构造函数'

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.colorreturn this.color,这应该解决问题。

this是javascript中的关键字,可以根据执行函数的上下文正确识别对象实例。

Players.Player.prototype.Piece = function () {
  return this.color //this is now valid
}
演示