如何调用以下功能和我的预期输出是"嗨约翰,我的名字是詹姆斯"
function Person(name){
this.name = name;
}
Person.prototype.greet = function(otherName){
return "Hi " + otherName + ", my name is " + name; // not working
}
名称未在上述代码中定义。
答案 0 :(得分:2)
使用this.name
function Person(name){
this.name = name;
}
Person.prototype.greet = function(otherName){
return "Hi " + otherName + ", my name is " + this.name;
}
var p = new Person("Foo");
console.log(p.greet("Bar")); // "Hi Bar, my name is Foo"

答案 1 :(得分:2)
访问此对象上附加的属性,嗯..您必须调用this.
function Person(name){
this.name = name;
}
Person.prototype.greet = function(otherName){
return "Hi " + otherName + ", my name is " + this.name;
}