You need to enable JavaScript to run this app. 能否在同一个代码块中为构造函数及其原型同时分配属性?
优惠活动
大模型
产品
解决方案
定价
更多

能否在同一个代码块中为构造函数及其原型同时分配属性?

实现方案

你之前的写法失效是因为内层Object.assign的第一个参数是构造函数的prototype对象,Object.assign会返回第一个参数本身,所以最终赋值给FirstClass的是原型对象,而非构造函数。

最直接易读的实现方式是使用立即执行函数表达式(IIFE),把构造函数定义、静态属性赋值、原型属性赋值的所有逻辑封装在同一个代码块内:

const Collection = {
    FirstClass: (function () {
        // 定义构造函数
        const Constructor = function() {
            this.propertyTheSecond = 'i am not a default';
        };
        // 赋值静态属性
        Object.assign(Constructor, {
            staticProperty: 42
        });
        // 赋值原型属性
        Object.assign(Constructor.prototype, {
            propertyTheFirst: 'hello i am a default'
        });
        // 返回构造函数作为FirstClass的值
        return Constructor;
    })()
    // 其他代码
};

如果追求更短的写法,也可以用逗号表达式实现,逻辑和IIFE一致:

const Collection = {
    FirstClass: (
        fn => (
            Object.assign(fn, { staticProperty: 42 }),
            Object.assign(fn.prototype, { propertyTheFirst: 'hello i am a default' }),
            fn
        )
    )(function() {
        this.propertyTheSecond = 'i am not a default';
    })
};

两种方案都可以把三类相关逻辑完全聚合在同一个代码块内,不会出现代码分散的问题。


内容的提问来源于stack exchange,提问作者Jared Brandt

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.21 05:54:04