Javascript:是否有关键字用于引用对象中的当前节点?

请考虑以下代码:
function Animal(){
  this.type = "dog";
  this.color = {
                 stomach: "white",
                 paws: "brown",
                 face: function(){
                   if(this.color.stomach === "white"){
                      return "red";
                   }else{
                      return "blue";
                   }
                 }
}
这种颜色奇怪的狗的脸颜色取决于他的胃的颜色。我想知道是否有更复杂的语法编写“this.color.stomach”部分。即,“this”指的是主要的Animal对象。是否有类似的关键字引用调用该关键字的父对象?例如,因为我已经在Animal.color中,而不是必须重复该部分来获得它的胃颜色(Animal.color.stomach),有没有办法直接引用颜色属性,所以它将是比如“parent.stomach”,其中“parent”指的是它被调用的任何属性 - 在这种情况下,Animal.color?     
已邀请:
你尝试过运行代码吗?因为
this
实际上是指
color
而不是
Animal
对象。 这是它的工作原理:
this
指的是调用函数的任何对象,在正常情况下,你的
face
函数将被称为
someAnimal.color.face()
- 在这种情况下,
this
已经引用了
color
对象,所以
this.color
将是一个错误而
this.stomach
实际上会起作用。     
function Color(data) {
    this.stomach = data.stomach;
    this.face = data.face;
}

function Animal() {
    var self = this; // self now refers to the animal
    this.type = "Dog";
    this.color = new Color({
        face: function() {
            // in the "face" function, "this" refers to the color
            if (this.stomach === "white") { // color's stomach
                return "red";
            } else if (self.type === "Dog") { // animal's type
                return "Blue";
            }
        }
   });
}
    

要回复问题请先登录注册