Javascript 如何获取构造函数';构造函数(JS)中的父函数

Javascript 如何获取构造函数';构造函数(JS)中的父函数,javascript,Javascript,我有一个有点复杂的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, th

我有一个有点复杂的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"
我希望我对我的问题描述得足够好。我希望能够返回构造函数paret的颜色,这意味着用更好的命令替换
this.parent.color
,该命令将在第一块上返回“黑色”,在第二块上返回“白色”


谢谢大家!

首先,您的代码中有一个输入错误

Players.Player.prototpe.Piece
应该是
Players.Player.prototype.Piece

如果您使用的是像chrome这样的浏览器,您可以通过启动开发者控制台轻松查看并修复这些错误。看

现在转到返回颜色的实际问题,您必须修改代码

返回此.parent.color
返回此.color
。这应该可以解决问题

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

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