对象源中的JavaScript错误
这是我第一次在JS中创建对象 有人能帮我理解为什么sourve不起作用吗 这是完整的来源:对象源中的JavaScript错误,javascript,Javascript,这是我第一次在JS中创建对象 有人能帮我理解为什么sourve不起作用吗 这是完整的来源: <script> function person(firstname,lastname,age,eyecolor) { this.firstname=firstname; this.lastname=lastname; this.age=age; this.eyecolor=eyecolor; function getName() {
<script>
function person(firstname,lastname,age,eyecolor) {
this.firstname=firstname;
this.lastname=lastname;
this.age=age;
this.eyecolor=eyecolor;
function getName() {
return this.firstname;
}
}
var myFather = new person("John","Doe",50,"blue");
document.write( myFather.getName() );
</script>
职能人员(名字、姓氏、年龄、眼睛颜色){
this.firstname=firstname;
this.lastname=lastname;
这个。年龄=年龄;
this.eyecolor=eyecolor;
函数getName(){
返回这个.firstname;
}
}
var myFather=新人(“约翰”、“多伊”、50、“蓝色”);
document.write(myFather.getName());
应该是
this.getName = function () {
return this.firstname;
}
最好将这种方法附加到person
的原型上
person.prototype.getName = function () {
return this.firstname;
}
这是代码
<script>
function person(firstname,lastname,age,eyecolor) {
this.getName = function getName() {
return firstname;
}
}
document.write( (new person("John","Doe",50,"blue")).getName() );
</script>
职能人员(名字、姓氏、年龄、眼睛颜色){
this.getName=函数getName(){
返回名字;
}
}
document.write((新人(“约翰”、“多伊”、50、“蓝色”)).getName();
你能解释一下原因吗?@ZaheerAhmed说来话长,但这可能会有所帮助:
<script>
function person(firstname,lastname,age,eyecolor) {
this.getName = function getName() {
return firstname;
}
}
document.write( (new person("John","Doe",50,"blue")).getName() );
</script>