简体   繁体   English

通过javascript中的名称访问函数的包含对象

[英]Accessing the containing object of a function by name in javascript

I'm wondering if somebody can comment (with citations) on whether the following is correct or will fail at some point? 我想知道是否有人可以(以下引用)发表评论,以下内容是否正确或在某个时候会失败?

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

I believe that this is the better way to return x, however one of my colleagues prefers to bind to this.x and use that. 我相信这是返回x的更好方法,但是我的一位同事更喜欢绑定到this.x并使用它。

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

I cannot find any specific examples that support me ( maybe because I'm wrong? ). 我找不到任何支持我的具体示例(也许是因为我错了?)。

I think the 2nd solution is better. 我认为第二种解决方案更好。

Consider this: 考虑一下:

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

But if you use this instead, you won't have the problem. 但是,如果使用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 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM