0

I have following code :

function A() {
  this.value = 'a_value';
}

A.prototype.getValue = function(){
   console.log(this.value); // got undefined, expected 'a_value'
}

setTimeout(new A().getValue, 100);

why i get this.value as undefined.? and how how do i access this.value?

EDIT : i am not allowed to change the setTimeout line (last line) of code.

2 Answers2

2

Hint: have you tried console.log(this);?

You are only passing the getValue function to setTimeout, not its context. Something like this would work: setTimeout(function() {new A().getValue();},100); But without changing that last line, there's basically nothing you can do.

Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
  • this is `window`. Are you really sure?, there any other way to solve problem, without changing the last line. – user3585284 Apr 08 '15 at 16:24
  • basically i just don't want to manually call `getValue` function. i just want to get it called automatically somehow after passing `getValue` as a callback. – user3585284 Apr 08 '15 at 16:27
1

you can avoid using the this altogether and not having this kind of problems with the following technique :

var A = function () { // no new no this
    var value = 'a_value';
    var getValue = function(){
        console.log(value);
    };
    return Object.freeze({
        getValue ,
    });
};

setTimeout(A().getValue, 100);

or write

var a = new A();

before, and then

setTimeout(a.getValue.bind(a), 100);
Walle Cyril
  • 3,087
  • 4
  • 23
  • 55