/* example 1 */
function Foo(radius) {
this.radius = radius;
}
Object.defineProperty(Foo.prototype, "radius", {
get: function() {
return this._radius;
},
set: function(val) {
if (!Number.isInteger(val)) {
console.log("radius must be an integer.");
}
this._radius = val;
}
});
Foo.prototype.area = function() {
return Math.pow(this.radius, 2) * Math.PI;
};
Foo.draw = function() {
console.log("drawing a circle with radius " + this.radius);
}
var foo = new Foo(10);
console.log(Object.getOwnPropertyNames(foo));
// ["_radius"]
/* example 2 */
function Bar(radius) {
this.radius = radius;
}
Object.defineProperty(Bar.prototype, "radius", {
get: function() {
return this._radius;
},
set: function(val) {
if (!Number.isInteger(val)) {
console.log("radius must be an integer.");
}
this._radius = val;
}
});
Bar.prototype = {
area: function() {
return Math.pow(this.radius, 2) * Math.PI;
}
};
Bar.draw = function() {
console.log("drawing a circle with radius " + this.radius);
}
var bar = new Bar(10);
console.log(Object.getOwnPropertyNames(bar));
// ["radius"]
上面2个例子为什么会有不同的输出?
1)如果Foo的原型链中有同名的属性,并且定义了set方法,那么radius属性就不会新建到Foo的实例对象上,而是直接使用原型链的属性,所以radius不会成为foo对象的ownProperty
2)和1不同之处在于Bar.prototype被重新定义了,通过前一个方法Object.defineProperty定义的radius属性已经被抹掉。所以radius属性通过new操作新建到实例对象上了,故其为bar对象的ownProperty
参考《你不知道的JavaScript》一书