javascript - getOwnPropertyNames输出?
天蓬老师
天蓬老师 2017-04-10 15:41:58
[JavaScript讨论组]

/* 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)
怪我咯

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

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

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号