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

Accessing the containing object of a function by name in javascript

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

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

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

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

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

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

考虑一下:

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