在学习对象原型时,我遇到了以下示例。
function Person(first, last, age, eye) {
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eye;
}
Person.prototype.name = function() {
return this.firstName + " " + this.lastName
};
var myFather = new Person("John", "Doe", 50, "blue");
alert(myFather.name);
当我尝试使用html页面通过浏览器运行时,会弹出以下警告消息。
function() {
return this.firstName + " " + this.lastName
}
因此,它不是返回'John Doe',而是将整个函数作为字符串返回。 如何解决这个问题?
PS:我使用VS Code,我使用node.js live-server在浏览器中运行。
答案 0 :(得分:-1)
你必须调用函数
alert(myFather.name());
答案 1 :(得分:-1)
您需要使用()
myFather.name()
function Person(first, last, age, eye) {
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eye;
}
Person.prototype.name = function() {
return this.firstName + " " + this.lastName
};
var myFather = new Person("John", "Doe", 50, "blue");
console.log(myFather.name());
答案 2 :(得分:-1)
您需要通过这种方式执行该功能myFather.name()
var myFather = new Person("John", "Doe", 50, "blue");
alert(myFather.name());
答案 3 :(得分:-1)
这是您正在使用的功能。你可以像alert(myFather.name());