julew julew - 3 months ago 17
Javascript Question

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 i want to achieve, is get the
foo_value
or
bar_value
after clicking the corresponding
button
.

I know, that i can do it just by checking
if(theVar==foo)
, but i am trying to find a way to get the scope of IIFE function (which wrapps the rest of code) and fetch variables foo and bar from it.
When i do
console.log(this)
(i thought it will point the owning function), but i get
window
object. I also tried to get to this variable dom window scope, but nothing worked properly.
Is there and option for doing this?

Answer

Could you try this here

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

can be replaced with

function getVar(theVar){
 console.log(foo);
 console.log(bar);
 //the code...
}       

this[foo] would return undefined:

  1. this here is the context of the inner function i.e. getVar
  2. Even if this were the outer context, the outer function does not have an object key by the name of foo. Instead, it has variables. If in fact you want to use this 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 a 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>