0

I'm trying to declare and use a function inside a function in this class, but it gives me an "TypeError: this.outputName is not a function" and I can't figure out an answer myself.

Any help is apreciated, snippet ahead.

var TestPerson = function(name) {

    this.name = name;
    
};
TestPerson.prototype.outputName = function()
{
    console.log('Name: ' + this.name);
};
TestPerson.prototype.outputNameWithDelay = function(delay)
{
    setTimeout(function() {
        this.outputName();
    }, delay);
    
};


var tp = new TestPerson('Mike', 28);

console.log('calling outputName');
tp.outputName();;

console.log('calling outputNameWithDelay 2s');
tp.outputNameWithDelay(2000);
console.log('waiting for Timeout...');

And already tried not to declare the function in the timeout there, but as a seperate function in the class, but still the same error.

var TestPerson = function(name) {

    this.name = name;
    
};
TestPerson.prototype.outputName = function()
{
    console.log('Name: ' + this.name);
};
TestPerson.prototype.outputNameWithDelay = function(delay)
{
    setTimeout(this.timeoutFunc, delay);
    
};
TestPerson.prototype.timeoutFunc = function()
{
    this.outputName();
};


var tp = new TestPerson('Mike');

console.log('calling outputName');
tp.outputName();;

console.log('calling outputNameWithDelay 2s');
tp.outputNameWithDelay(2000);
console.log('waiting for Timeout...');

Thanks in advance!

dreiekk
  • 113
  • 4
  • 13

0 Answers0