javascript - 在类中不使用扩展运算符合并对象属性
问题描述
我试图在没有传播运算符的情况下在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);
解决方案
推荐阅读
- java - setText doesn't work properly if the string starts with a negative sign
- javascript - 将 RestSharp Reqest AddParameter 转换为 POST 请求的 JavaScript 数据
- assembly - AVR 字节存储
- multithreading - 多核架构 VS 多线程
- javascript - Javascript 引用索引之类的枚举、重构
- node.js - InputException 发生在 GetStream.io 中,当尝试为 NodeJS 的活动表单添加反应时
- unity3d - 在游戏视图中,相机速度是完美的,但在手机中测试时相机速度要慢得多
- java - Spring Cloud Stream 自定义 binder 未注册。如果使用 @Configuration 则禁用 kafka binder
- google-docs - Google Docs API - 更新链接表
- c - C 中的 gets() 函数是否会在输入字符串的末尾自动添加一个 NULL 字符?