请教一个关于Javascript原型的问题:
巴扎黑
巴扎黑 2017-04-11 10:28:27
[JavaScript讨论组]
function FunctionClass() {
    this.name = "test";
}

FunctionClass.prototype = {
    setVal: function() {
        console.log("xxx");
    }
}

console.log(FunctionClass.prototype.constructor === FunctionClass)

会有什么问题?
可否举几个例子,先谢过大家。

巴扎黑
巴扎黑

全部回复(4)
天蓬老师
function FunctionClass() {
    this.name = "test";
}

FunctionClass.prototype.setVal = function() {
        console.log("xxx");
    
}

console.log(FunctionClass.prototype.constructor === FunctionClass)//true
大家讲道理

FunctionClass.prototype = {} 你这样写本质上重写了默认的prototype对象,因此constructor属性也变成了新的对象的constructor属性(指向Object构造函数),不再指向FunctionClass函数。

另外重设constructor属性会导致它的[[Enumerable]]特性被设置为true。默认情况下,原生的constructor属性是不可枚举的,可以使用Object.defineProperty():

Object.defineProperty(FunctionClass.prototype, "constructor", {
    enumerable: false,
    value: FunctionClass
});

---- 参见红宝书155页。

阿神

FunctionClass.prototype变成了Object

大家讲道理

用 FunctionClass.prototype 这一条会重写原型链导致 constructor 丢失变为 Object。
建议这么写:

function FunctionClass() {
    this.name = "test";
}
FunctionClass.prototype.setVal = function () {
   console.log("xxx");
}

或者在重写prototype后,将 constructor 重置为 FunctionClass。

FunctionClass.prototype.constructor = FunctionClass
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

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