function Name(first, last) {
this.first = first;
this.last = last;
this.fullName = first + " " + last
}
Name.prototype = {
get fullName() {
return this.first + " " + this.last;
},
set fullName(name) {
var names = name.split(" ");
this.first = names[0];
this.last = names[1];
}
};
var person = new Name("Foo", "Bar");
// person.fullName = "Foo Bar"
person.hasOwnProperty("fullName") // false
有没有办法返回属性?
最佳答案
正如InvernoMuto指出的那样,Object.hasOwnProperty("fullName")
返回false
,因为它不是person
的自身属性;它是通过原型(prototype)链继承的。在构造函数中使用this.fullName = "...";
时,您是在调用继承的setter,而不是添加新属性。
如果要查找此类属性,可以:
for..in
循环:for (var prop in person) {
// this will iterate over EVERY property in person's prototype chain
}
function Name(first, last) {
this.first = first;
this.last = last;
Object.defineProperty(this, "fullName", {
get: function() {
return this.first + " " + this.last;
},
set: function(name) {
var names = name.split(" ");
this.first = names[0];
this.last = names[1];
}
});
}
var person = new Name("Ronald", "McDonald");
console.log(person.hasOwnProperty("fullName")); // true
new
关键字,而只是调用以下函数:function Name(first, last) {
return {
first: first,
last: last,
get fullName() { return this.first + " " + this.last; },
set fullName(name) {
var names = name.split(" ");
this.first = names[0];
this.last = names[1];
}
};
};
var person = Name("Ronald", "McDonald");
console.log(person.hasOwnProperty("fullName")); // true