通过构造函数显示函数时出现问题.我的函数一直显示:(



(刚启动JS和第一个堆栈溢出,对不起任何愚蠢

我正在尝试弄清楚如何通过 JS 构造函数插入函数的结果。我可以用字符串等简单的东西来做到这一点,但是当我尝试使用简单的函数来寻找答案时,我的新手头脑一片空白。

JS代码:

var Person = function(name, yearOfBirth, job, gender) {
    this.name = name;
    this.yearOfBirth = yearOfBirth;
    this.job = job;
    this.gender = gender;
}
Person.prototype.calculateAge = function () {
        console.log(2018 - this.yearOfBirth);
    }
Person.prototype.intro = function () {
        console.log(this.noun + ' name is ' + this.name + ' ' +this.lastName + ' and is ' + (2018 - this.yearOfBirth));
    }
Person.prototype.lastName = 'Smith';
Person.prototype.noun = function () {
        if(this.gender === 'male'){
        console.log('his');
    } else {
        console.log('her');
    }
}
var craig = new Person('Craig', 1984, 'student', 'male');
var jane = new Person('Jane', 1969, 'designer', 'female');
craig.intro();
jane.intro();

控制台中的结果只是一个:

function () {
        if(this.gender === 'male'){
        console.log('his');
    } else {
        console.log('her');
    }
} name is Craig Smith and is 34

我正在寻找的是:他的名字是克雷格史密斯,今年 34

(简也一样,但和她在一起,而且年纪大了很多。

再一次,新手正在参加一些在线课程。浏览了一下问题,没有看到任何有帮助的东西。

如果你能向我解释这一点,我将不胜感激!是否链接到包含信息的网站,或者您是否想解释。

所有的帮助都是有帮助的! :)

有几点不对劲:

  1. 您实际上并没有调用this.noun函数,这就是它打印函数定义的原因。你想要打印函数在被调用后返回的内容。
  2. 考虑到这一点,您希望像这样调用(调用(函数:this.noun()
  3. 最好让this.noun()返回字符串而不是console.log以便获得所需的输出。所以你的代码变成了这样:

    var Person = function(name, yearOfBirth, job, gender) {
        this.name = name;
        this.yearOfBirth = yearOfBirth;
        this.job = job;
        this.gender = gender;
    }
    Person.prototype.calculateAge = function () {
            console.log(2018 - this.yearOfBirth);
        }
    Person.prototype.intro = function () {
            console.log(this.noun() + ' name is ' + this.name + ' ' +this.lastName + ' and is ' + (2018 - this.yearOfBirth));
        }
    Person.prototype.lastName = 'Smith';
    Person.prototype.noun = function () {
        if(this.gender === 'male'){
            return 'his';
        } else {
            return 'her';
        }
    }
    var craig = new Person('Craig', 1984, 'student', 'male');
    var jane = new Person('Jane', 1969, 'designer', 'female');
    craig.intro();
    jane.intro();
    

输出:

his name is Craig Smith and is 34
her name is Jane Smith and is 49

最新更新