Javascript 能否为同一块中的对象及其原型指定特性?

Javascript 能否为同一块中的对象及其原型指定特性?,javascript,Javascript,我想创建一个构造函数,并为它和它的原型分配一些属性。为了压缩代码并将类似的想法分组,我想在同一块中找到一种方法 例如: const Collection = { FirstClass: function() { this.propertyTheSecond = 'i am not a default'; } // insert a buuunch of code here }; Collection.FirstClass.staticPrope

我想创建一个构造函数,并为它和它的原型分配一些属性。为了压缩代码并将类似的想法分组,我想在同一块中找到一种方法

例如:

const Collection = {

    FirstClass: function() {

        this.propertyTheSecond = 'i am not a default';

    }

    // insert a buuunch of code here

};

Collection.FirstClass.staticProperty = 42;

Collection.FirstClass.prototype.propertyTheFirst = 'hello i am a default';
我想把它压缩成一个块,这样三种“类型”的块就不会彼此分离

我可以使用
staticProperty
来实现这一点,但我不确定如何使用
propertyTheFirst
实现这一点

const Collection = {

    FirstClass: Object.assign( function() {

        this.propertyTheSecond = 'i am not a default';

    }, {

        staticProperty: 42

    } )

    // insert a buuunch of code here

};

Collection.FirstClass.prototype.propertyTheFirst = 'hello i am a default';
我希望有这样的事情:

const Collection = {

    FirstClass: Object.assign( Object.assign( function() {

        this.propertyTheSecond = 'i am not a default';

    }, {

        staticProperty: 42

    } ).prototype, {

        propertyTheFirst: 'hello i am a default'

    } )

    // insert a buuunch of code here

};
但是,这不起作用,因为最终返回值是原型,而不是构造函数

有没有一个相当简单的方法来做到这一点,我错过了??谢谢

有没有一种简单的方法可以做到这一点,而我却没有

如果您的目标是对相关代码进行逻辑分组,那么最直接和现代的方法是使用与第一个示例类似的内容,但将其隔离在自己的模块中,并导出
集合
,而不会混淆链接的
对象。分配
s。如果
集合
和分配给它的属性是模块中唯一的代码,那么很容易理解

另一种方法是使用iLife:

const Collection = (() => {
    const Collection = {

        FirstClass: function() {

            this.propertyTheSecond = 'i am not a default';

        }

        // insert a buuunch of code here

    };

    Collection.FirstClass.staticProperty = 42;

    Collection.FirstClass.prototype.propertyTheFirst = 'hello i am a default';
    return Collection;
})();
从技术上讲,可以使用
Object.assign
s执行此操作,但我不推荐使用:

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

我应该检查一下。。但我甚至没有尝试这样做,因为我认为这会覆盖原型,而不是递归地赋值。但你的意见很有价值!也许我应该让它更模块化