繁体   English   中英

如何在构造函数(JS)中获取构造函数的父级

[英]How to get the constructor's parent inside the constructor function (JS)

我的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.colorreturn this.color应该可以解决问题。

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

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

DEMO

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM