gpt4 book ai didi

javascript - 对象的原型(prototype)方法仅返回函数定义,不执行。

转载 作者:行者123 更新时间:2023-11-28 17:15:38 25 4
gpt4 key购买 nike

我正在审查创建和“实例化”对象的原型(prototype)方法,但遇到了问题。当我将此代码放入浏览器的控制台进行测试时,如果我输入:

nUser1.myAge()  // only the function definition is returned, doesn't actually execute.

我想也许我需要在该方法上有一个 return 语句,但这没有什么区别。另外,在我之前的(成功的)实践尝试中,他们不需要 return 语句来返回相应方法的输出。

我已经多次查看代码并将其与我的其他示例进行比较,但没有什么突出的地方。我觉得问题就在我眼皮子底下,但我没有看到它。

function normUserCreator(name, age, employed) {
this.name = name;
this.age = age;
this.employed = employed;
};

normUserCreator.prototype.myName = function() {
console.log("My name is: " + this.name + ".")
};
normUserCreator.prototype.myAge = function() {
console.log("My age is : " + this.myAge + ".")
};
normUserCreator.prototype.employed = function() {
if (this.employed === true) {
console.log("I am employed");
} else if (this.employed === false) {
console.log("I am not employed");
}
};

var nUser1 = new normUserCreator('Kevin', 26, false);

最佳答案

错误在这一行

console.log("My age is : " + this.myAge + ".")

它基本上是在调用自身。将其替换为 this.age

您还可以将 if (this.owned === true) 替换为 if (this.owned) ,对于 else if 条件相同

function normUserCreator(name, age, employed) {
this.name = name;
this.age = age;
this.employed = employed;
};

normUserCreator.prototype.myName = function() {
console.log("My name is: " + this.name + ".")
};
normUserCreator.prototype.myAge = function() {
console.log("My age is : " + this.age + ".")
};
normUserCreator.prototype.employed = function() {
if (this.employed) {
console.log("I am employed");
} else if (!this.employed) {
console.log("I am not employed");
}
};

var nUser1 = new normUserCreator('Kevin', 26, false);
nUser1.myAge()

关于javascript - 对象的原型(prototype)方法仅返回函数定义,不执行。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53522967/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com