getOwnPropertyNames输出?

/* 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个例子为什么会有不同的输出?

阅读 2.3k
1 个回答

1)如果Foo的原型链中有同名的属性,并且定义了set方法,那么radius属性就不会新建到Foo的实例对象上,而是直接使用原型链的属性,所以radius不会成为foo对象的ownProperty
2)和1不同之处在于Bar.prototype被重新定义了,通过前一个方法Object.defineProperty定义的radius属性已经被抹掉。所以radius属性通过new操作新建到实例对象上了,故其为bar对象的ownProperty

参考《你不知道的JavaScript》一书

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题