Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get 'this' value of caller function?

If I have a function like this:

function foo(_this) {
    console.log(_this);
}

function bar() {}
bar.prototype.func = function() {
    foo(this);
}

var test = new bar();
test.func();

then the test instance of bar gets logged.

However, for this to work I have to pass the this in the bar.prototype.func function. I was wondering whether it is possible to obtain the same this value without passing this.

I tried using arguments.callee.caller, but this returns the prototype function itself and not the this value inside the prototype function.

Is it possible to log the test instance of bar by only calling foo() in the prototype function?

like image 396
pimvdb Avatar asked Jun 13 '11 14:06

pimvdb


3 Answers

If the question is 'without passing this (by any means)' then answer is no

value can be passed by alternative methods though. For example using global var (within Bar class) or session or cookies.

    function bar() {

      var myThis;

      function foo() {
          console.log(myThis);
      }

      bar.prototype.func = function() {

          myThis = this;
           foo();
      }
   }

   var test = new bar();
   test.func();
like image 119
Scherbius.com Avatar answered Oct 16 '22 03:10

Scherbius.com


I think calling foo within the context of bar should work:

function foo() {
    console.log(this.testVal);
}

function bar() { this.testVal = 'From bar with love'; }
bar.prototype.func = function() {
    foo.call(this);
}

var test = new bar();
test.func(); //=> 'From bar with love'
like image 39
KooiInc Avatar answered Oct 16 '22 01:10

KooiInc


What about this?

"use strict";
var o = {
    foo : function() {
        console.log(this);
    }
}

function bar() {}
bar.prototype = o;
bar.prototype.constructor = bar;
bar.prototype.func = function() {
    this.foo();
}

var test = new bar();
test.func();

Or this:

"use strict";
Function.prototype.extender = function( o ){
    if(typeof o ==  'object'){
        this.prototype = o;
    }else if ( typeof o ==  'function' ) {
        this.prototype = Object.create(o.prototype);
    }else{
        throw Error('Error while extending '+this.name);
    }
    this.prototype.constructor = this;
}
var o = {
    foo : function() {
        console.log(this);
    }
}

function bar() {}
bar.extender(o);
bar.prototype.func = function() {
    this.foo();
}

var test = new bar();
test.func();
like image 40
Samuel Nakombi Avatar answered Oct 16 '22 01:10

Samuel Nakombi