我有这个人对象
function person(first, last, age, eye) {
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eye;
function sayName(){
var full="";
full="Hello my name is "+this.firstName + " "+this.lastName;
}
}
并制作了这个对象的实例
var raul = new person("Raul","Zamora","19","brown")
我无法弄清楚为什么函数sayName不起作用。我正在实施它:
document.getElementById("sayName").innerHTML=raul.sayName();
其中sayName
已被定义为HTML部分的ID。
答案 0 :(得分:2)
它不起作用,因为sayName
函数仅在构造函数的范围内可见(因此完全没用)。
要在实例上使用该功能,请使用
person.prototype.sayName = function(){
var full="Hello my name is "+this.firstName + " "+this.lastName;
return full; // don't forget to return the string
}
有关详情,请参阅MDN的这篇文章:Introduction to Object-Oriented JavaScript
答案 1 :(得分:0)
您的功能sayName
不属于您的班级,为此,您需要使用this
或使用propotype
使用this
:
function person(first, last, age, eye) {
this.sayName = function(){
return "Hello my name is "+this.firstName + " "+this.lastName;
}
}
使用prototype
:
person.prototype.sayName = function(){
return "Hello my name is "+this.firstName + " "+this.lastName;
}
另外sayName
没有返回任何内容。
答案 2 :(得分:0)
你在那里有一个本地函数声明。通过赋值使其成为对象的属性 - 就像您编写this.firstName = first
not var firstName = first
一样。
这将使它成为一种可从外部访问的方法:
function person(first, last, age, eye) {
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eye;
this.sayName = function sayName(){
var full="Hello my name is "+this.firstName + " "+this.lastName;
};
}
然而,有些反对意见:
sayName
方法需要return
字符串,否则您的示例调用将无法正常工作所以我们到了
function Person(first, last, age, eye) {
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eye;
}
Person.prototype.sayName = function sayName(){
return "Hello my name is "+this.firstName + " "+this.lastName;
};
var raul = new Person("Raul","Zamora","19","brown");
document.getElementById("sayName").textContent = raul.sayName();