1

考虑以下代码:

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?

4

2 回答 2

2

你试过运行你的代码吗?因为this实际上确实指的是color而不是Animal对象。

它是这样工作的:this引用函数被调用的任何对象,并且在正常情况下,您的face函数将被称为someAnimal.color.face()- 在这种情况下,this已经引用了该color对象,因此在实际工作this.color时会出错。this.stomach

于 2011-02-12T20:50:49.380 回答
1
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";
            }
        }
   });
}
于 2011-02-12T21:00:59.533 回答