簡體   English   中英

從函數訪問JavaScript對象變量

[英]Access JavaScript object variable from function

我下面有以下代碼,但是有一個問題。 我想從調用匿名函數的名為the_id的函數clslevel()內部訪問一個變量。 我嘗試了this.the_id,但返回的是未定義的。

 function clslevel(id){ var the_id = id; this.methodOne=function(param){ param(); return this; }; this.methodTwo=function(param){ param(); return this; }; } function level(id){ return new clslevel(id); } level("myButton") .methodOne( function(){ console.log("methodOne called."); // how can I access the variable 'the_id' in clslevel() from here? } ) .methodTwo( function(){ console.log("methodTwo called"); } ) 

先感謝您!

將其作為參數傳遞給函數,如下所示:

 function clslevel(id){ var the_id = id; this.methodOne=function(param){ param(the_id); return this; }; this.methodTwo=function(param){ param(); return this; }; } function level(id){ return new clslevel(id); } level("myButton") .methodOne( function(the_id){ console.log("methodOne called.", the_id); // You have the_id here } ) .methodTwo( function(){ console.log("methodTwo called"); } ) 

您可以將此變量傳遞給回調:

function clslevel(id){ 
  var the_id = id;
  this.methodOne=function(param){
    param(the_id);
    return this;
  };
  this.methodTwo=function(param){
    param();
    return this;
  };

}


function level(id){
  return new clslevel(id);
}



level("myButton")
  .methodOne(
    function(passed_id){
      console.log("methodOne called.");
      console.log(passed_id)
      // how can I access the variable 'the_id' in clslevel() from here?
    }  
  )
  .methodTwo(
    function(){
      console.log("methodTwo called");
    }  
  )

您可以傳遞對象的引用,以便可以在其他作用域內使用父函數

 function clslevel(id){ this.the_id = id; this.methodOne=function(param){ param(this); return this; }; this.methodTwo=function(param){ param(this); return this; }; } function level(id){ return new clslevel(id); } level("myButton") .methodOne( function(parent){ console.log("methodOne called."); console.log('the_id = ' + parent.the_id) // how can I access the variable 'the_id' in clslevel() from here? } ) .methodTwo( function(){ console.log("methodTwo called"); } ) 

暫無
暫無

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

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