函数中的JavaScript函数-TypeError:this.outputName不是函数

时间:2018-06-22 08:13:23

标签: javascript function class typeerror

我正在尝试在此类中的函数内部声明和使用函数,但是它给我一个“ TypeError:this.outputName不是函数”,我自己也找不到答案。

任何帮助都非常重要,摘要如下。

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...');

并且已经尝试不在该超时中声明该函数,而是将其作为类中的单独函数,但仍然是相同的错误。

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...');

谢谢!

0 个答案:

没有答案