【问题标题】:Playing with "this" in Javascript在 Javascript 中玩“this”
【发布时间】:2013-11-24 01:23:29
【问题描述】:

给定:

    var q = {};
    q.id = 1234;
    q.bonus = {
        'a':{
            'b':(function(){
                //i want to access q.id
                var id = this. ??? .id
            }),
        }
    };

应该是什么???访问 q.id。

【问题讨论】:

  • 使用 q.id 不行
  • 没有任何内置的“父指针”。如果您希望嵌入对象a 能够引用q,那么您必须明确包含它:'a': { 'parent': q, ...

标签: javascript node.js this


【解决方案1】:

正如您从其他答案和 cmets 中看到的那样,任何解决方案都涉及按名称引用 q。因此,我会直接使用q.id

【讨论】:

    【解决方案2】:

    您可以使用 call 或 apply 来更改 'this' 的值。

    var q = {};
    q.id = 1234;
    q.bonus = {
        'a':{
            'b':(function(){
                //i want to access q.id
                var id = this.id
            }.call(q)),
        }
    };
    

    【讨论】:

    • 这会立即调用函数
    【解决方案3】:

    要在绑定到b 的函数中访问q.id,请使用Function.prototype.bind

    var q = {};
    q.id = 1234;
    q.bonus = {
      'a':{
         'b': (function(){
           //i want to access q.id
           var id = this.id;
           console.log(id);
         }).bind(q),
      }
    };
    
    q.bonus.a.b();
    

    你也可以使用Function.prototype.call来改变this的上下文

    q.bonus.a.b.call(q);
    

    【讨论】:

    • 我相信你也可以使用 call 函数。
    • 有趣的副作用,你不能在绑定函数上使用call。好吧,你可以,但它不会做你想做的事......
    猜你喜欢
    • 1970-01-01
    • 2019-01-02
    • 1970-01-01
    • 2014-02-20
    • 1970-01-01
    • 2015-01-22
    • 1970-01-01
    • 2021-10-19
    • 2023-03-03
    相关资源
    最近更新 更多