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()

1
  • This is one of the most well-covered over-discussed topics in JavaScript. Commented Aug 1, 2017 at 17:33

1 Answer 1

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;

Sign up to request clarification or add additional context in comments.

2 Comments

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 ?
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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.