问题
我想要创建一个类,生成的对象有默认属性,同时也可以通过传入参数的形式修改其默认属性。
例如:
我有一个person类 他有age 和 name两个属性 初始化的时候属性分别为18 和 towrabbit。但是创建新的person对象的时候,我可以重新定义对象的属性 比如 我可以只把age改了,改成22,或者 只改名字 改成’角角兔’。
解决
- Object.assign(target, …sources)
target为目标对象
sources为源对象
这个函数用于合并两个或多个对象
如果目标对象中的属性具有相同的键,则属性将被源中的属性覆盖。后来的源的属性将类似地覆盖早先的属性。
例子:
let obj1 = {
x: 0,
y: 0
}
let obj2 = {
x: 1,
y: 1,
z: 1
}
let obj3 = {
x: 4,
z: 2
}
let resultObj = Object.assign(obj1, obj2, obj3)
console.log(resultObj) // 打印结果 {x: 4, y: 1, z: 2, p: 10}
所以在类的构造函数中,就可以使用对象合并来更改某些属性
class point {
constructor( setting = {} ) {
Object.assign(this, {
x: 0,
y: 0,
color: '#000000',
fill: false
}, setting )
}
}
//使用
let point1 = new point( {
x: 2,
y: 10,
fill: true,
name: 'aaaaa'
})
console.log(point1) //打印结果 point {x: 2, y: 10, color: "#000000", fill: true, name: "aaaaa"}
另外还有一种方式不会合并对象,也没法添加在类中不存在的属性,但是可以实现合并已有的属性,当然用的也是es6的新特性:
class point {
constructor( {x = 0, y = 0, fill = true, color = '#000000'} = {x: 0,y: 0,fill: true,color: '#000000'} ) {
this.x = x;
this.y = y;
this.fill = fill;
this.color = color;
}
}
let point2 = new point({ x: 2, name: 'aaaa' })
// 打印结果 point {x: 2, y: 0, fill: true, color: "#000000"}
后面这个不会将构造函数中不存在的属性添加进去,例子中 name属性就没有添加到实例中
- 这里是角角兔 towrabbit
- 欢迎点赞评论哦