比如,一个字面量对象:var person = {
firstName: 'Jim',
lastName: 'Green',
fullName: firstName + ' ' + lastName
}上面的代码是有误的,fullName是无法这样引用
person的firstName和lastName属性的(原因就不说了)。要解决这个问题,可以将fullName改为一个函数,如:var person = {
firstName: 'Jim',
lastName: 'Green',
fullName: function (){ return this.firstName + ' ' + this.lastName;}
}
alert(person.fullName());
或者在person外定义firstName和lastName,如:var firstName = 'Jim',
lastName = 'Green';
var person = {
firstName: firstName,
lastName: lastName,
fullName: firstName + ' ' + lastName
}
但总觉得这样很不爽,不知大家有没有更好的办法?
firstName: 'Jim',
lastName: 'Green',
fullName: firstName + ' ' + lastName
}上面的代码是有误的,fullName是无法这样引用
person的firstName和lastName属性的(原因就不说了)。要解决这个问题,可以将fullName改为一个函数,如:var person = {
firstName: 'Jim',
lastName: 'Green',
fullName: function (){ return this.firstName + ' ' + this.lastName;}
}
alert(person.fullName());
或者在person外定义firstName和lastName,如:var firstName = 'Jim',
lastName = 'Green';
var person = {
firstName: firstName,
lastName: lastName,
fullName: firstName + ' ' + lastName
}
但总觉得这样很不爽,不知大家有没有更好的办法?
this.firstName = firstName;
this.lastName = lastName;
this.fullName = firstName + ' ' + lastName;
};
Person.prototype = {
showName:function(){alert(this.fullName);}
};
var p = new Person('x', 'y');
p.showName();
firstName: 'Jim',
lastName: 'Green',
fullName: function (){ return this.firstName + ' ' + this.lastName;}
}
这样不是很好
fullname 变成了一个只读属性 firstname 或者 lastname 变化了 他的值也变化
很正确
firstName: 'Jim',
lastName: 'Green'
}
person.fullName = person.firstName + ' ' + person.lastName;