javascript - How to get owner function of another function -


example on jsfiddle: https://jsfiddle.net/cg33ov4g/3/

(function($){     var foo='foo_value';     var bar='bar_value';      function getvar(thevar){       console.log(this[foo]);       console.log(this[bar]);       //the code...     }             $('.container').on('click', 'button', function(){         getvar(this.dataset.target);     }) }(jquery)) 

what want achieve, foo_value or bar_value after clicking corresponding button.

i know, can checking if(thevar==foo), trying find way scope of iife function (which wrapps rest of code) , fetch variables foo , bar it. when console.log(this) (i thought point owning function), window object. tried variable dom window scope, nothing worked properly. there , option doing this?

could try here

function getvar(thevar){   console.log(this[foo]);   console.log(this[bar]);   //the code... }        

can replaced

function getvar(thevar){  console.log(foo);  console.log(bar);  //the code... }        

this[foo] return undefined:

  1. this here context of inner function i.e. getvar
  2. even if this outer context, outer function not have object key name of foo. instead, has variables. if in fact want use approach, try this:

    (function($){ this.foo = 'foo_value'; this.bar = 'bar_value'; var self = this; function getvar(thevar){ console.log(self[foo]); console.log(self[bar]); //the code... }

    this.foo_value = "some random string"; this.bar_value = "some other string";  $('.container').on('click', 'button', function(){     getvar(this.dataset.target); })}(jquery)) 

see working example here

 (function($){          this.foo = 'foo_value';          this.bar = 'bar_value';          var self = this;          function getvar(thevar){            console.log(self[foo]);            console.log(self[bar]);            //the code...          }                   this.foo_value = "some random string";          this.bar_value = "some random string";               $('.container').on('click', 'button', function(){              getvar(this.dataset.target);          })      }(jquery))
<div class="container">  	<button data-target='foo'>foo</button>  	<button data-target='bar'>bar</button>  </div>


Comments