簡體   English   中英

在Javascript中使用“this”

[英]Playing with “this” in Javascript

鑒於:

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

應該是什么??? 訪問q.id.

要在綁定到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或apply來更改'this'值。

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

從其他答案和注釋中可以看出,任何解決方案都涉及通過名稱引用q 因此,我只是直接使用q.id

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM