0

This question is from an written test for a company. It looks very confusing. I thought it will print whatever this.name is set to. Bu when I typed the code it shows nothing. I have little knowledge about closures and I think it is related to the problem. I want a little explanation here.

function dd(name) {
  this.name = name;
  this.go = function() {
    setInterval(function() {
      return this.name;
    }, 2000)
  }
}
var tt = new dd("corolla");
tt.go()
4castle
  • 32,613
  • 11
  • 69
  • 106
salehin
  • 3
  • 3

1 Answers1

0

You can't get the return value from setInterval in this way. Try with a callback as in the following snippet

function dd(name)
{
  this.name=name;
  console.log( name );
  var _this = this;
  this.go=function(cb)
  {
    setInterval(function() {
        cb(_this.name);
    },1000)
  }
}
var tt=new dd("corolla");
tt.go(function(ret) {
    console.log( ret );
})

Also, please note that inside setInteval the value of this is not the same as in the otter function. That's why var _this=this;

Jarek Kulikowski
  • 1,399
  • 8
  • 9
  • Ohh i get it now. But have to say it's weird. If i am right inside setInterval normally this refers to window object. So i am actually declaring this in the global context of setInterval as a variable so that setInterval has access to object's name property, right ? – salehin Aug 01 '17 at 19:01
  • Yes, `setInterval` inside a function like this is a bit too 'hidden'. There are different ways of handling this, I just wanted to point out the use of a callback in this question. – Jarek Kulikowski Aug 01 '17 at 19:03