Доступ к объектной переменной JavaScript из функции - PullRequest
0 голосов
/ 02 ноября 2018

У меня есть следующий код ниже, но одна проблема. Я хочу получить доступ к переменной из функции clslevel () с именем the_id, из вызывающей анонимной функции. Я пробовал 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");
    }  
  )

спасибо заранее!

Ответы [ 3 ]

0 голосов
/ 02 ноября 2018

Вы можете передать эту переменную в обратный вызов:

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");
    }  
  )
0 голосов
/ 02 ноября 2018

Вы можете передать ссылку на ваш объект, чтобы вы могли использовать родительские функции внутри другой области действия

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");
    }  
  )
0 голосов
/ 02 ноября 2018

Передайте его в качестве параметра функции, например:

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");
    }  
  )
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...