首页 > 解决方案 > 在类中不使用扩展运算符合并对象属性

问题描述

我试图在没有传播运算符的情况下在es6 类上实现原型模式,但没有成功。

我想在画布上创建 10000000 颗星星,所以我认为这种模式将是完美的,因为根据定义

原型模式是软件开发中的一种创造设计模式。当要创建的对象类型由原型实例确定时使用,该实例被克隆以生成新对象。

到目前为止,这是我使用扩展运算符的工作代码:

    class Prototype {// Class
            constructor(options) {// constructor 
                this.options = options;//properties
                this.context = undefined;
            }        
            //Methods 
            clone (features){ 

                let clone = new Prototype(this.options); 

                clone.options = {...clone.options, ...features};
                //Object.assign(clone.options, features);

                return clone;
            }
        } 

        //object literal    
        var options ={
            width : 200,
            height: 100
        }    
        let prototype = new Prototype(options);  

        let clone = prototype.clone({ 
            height: 800,
            color: "red"
        } ); 
        console.log("prototype:::",prototype,"clone:::",clone); 

但是使用Object.assign,我得到这个根本不正确

    class Prototype {// Class
            constructor(options) {// constructor 
                this.options = options;//properties
                this.context = undefined;
            }        
            //Methods 
            clone (features){ 

                let clone = new Prototype(this.options); 

                //clone.options = {...clone.options, ...features};
                Object.assign(clone.options, features);

                return clone;
            }
        } 

        //object literal    
        var options ={
            width : 200,
            height: 100
        }    
        let prototype = new Prototype(options);  

        let clone = prototype.clone({ 
            height: 800,
            color: "red"
        } ); 
        console.log("prototype:::",prototype,"clone:::",clone); 

标签: javascriptperformanceecmascript-6

解决方案


推荐阅读