在javascript中按名称访问函数的包含对象

时间:2015-08-06 09:33:31

标签: javascript closures this

我想知道是否有人可以评论(引用)关于以下内容是否正确或在某些时候会失败?

var myObj = {  
    x: 10,
    getX: function getX() {
        return myObj.x;
    }
}

我相信这是返回x的更好方法,但我的一位同事更喜欢绑定到this.x并使用它。

var myObj = {  
    x: 10,
    getX: function getX() {
        var thisObj = this;
        return thisObj.x;
    }
}

我找不到任何支持我的具体例子(也许是因为我错了?)。

1 个答案:

答案 0 :(得分:2)

我认为第二种解决方案更好。

考虑一下:

var myObj = {  
  x: 10,
  getX: function getX() {
    return myObj.x;
  }
}

var anotherObj = myObj;

myObj.getX();      // return myObj.x
anotherObj.getX(); // ERROR, never return anotherObj.x

但如果您使用this代替,则不会出现问题。

var myObj = {
    x: 10,
    getX: function() { // you may not need the function name
        return this.x;
    }
};

var anotherObj = myObj;

console.log(myObj.getX());      // return myObj.x
console.log(anotherObj.getX()); // return anotherObj.x