-1

So i am self learning developer. I learned quite a lot of php and started doing javascript. I was introduced to javascript first class functions and all that. I learned that you can add new property (var or function) into class by prototype which is from my understanding object that has every other object (like variable, function). While trying prototype out i got problem with this code:

function Fox(color) {
  this.color = color;
}

Fox.prototype.speak = function() {
  console.log('I am ' + this.color);
};

var myFox = new Fox('blue');

window.setTimeout(myFox.speak, 1000);

this.color is undefined in this case and i am having hard time understanding why. It works like this but with no time delay. I think setTimeout not working properly is because of how it is made to work, to have function(first class) as argument not to execute function ( as it does if you put () ). Again don't know why this returns value blue.

            /* This works but with no time delay: */
            window.setTimeout(myFox.speak(), 1000);
            /* returns blue */
Scott Marcus
  • 57,085
  • 6
  • 34
  • 54
Vukasin Sevo
  • 67
  • 1
  • 5

1 Answers1

-1

Your problem - if first case: you lost context Try it:

 function Fox(color) {
                this.color = color;
            }
            Fox.prototype.speak = function() {
                console.log('I am ' + this.color);
            };
            var myFox = new Fox('blue');

 setTimeout(myFox.speak.bind(myFox), 1000);

also you can use callback with your method:

 function Fox(color) {
                this.color = color;
            }
            Fox.prototype.speak = function() {
                console.log('I am ' + this.color);
            };
            var myFox = new Fox('blue');

 setTimeout(function(){myFox.speak()}, 1000);