【发布时间】:2021-06-25 13:45:53
【问题描述】:
我正在学习 JS 中的组合概念。下面是我的演示代码。
moveBy 函数将值正确分配给 x 和 y。
但是,setFillColor 函数不会将传递的值分配给 fillColor。
调用setFillColor 函数时究竟发生了什么?
const withMoveBy = (shape) => ({
moveBy: (diffX, diffY) => {
shape.dimensions.x += diffX;
shape.dimensions.y += diffY;
},
});
const withSetFillColor = (shape) => ({
setFillColor: (color) => {
console.log(shape.fillColor); // 1
shape.fillColor = color;
shape.dimensions.fillColor = color;
console.log(shape.fillColor); // 2
},
});
const shapeRectangle = (dimensions) => ({
type: 'rectangle',
fillColor: 'white',
dimensions,
});
const shapeCircle = (dimensions) => ({
type: 'circle',
fillColor: 'white',
dimensions,
});
const createShape = (type, dimensions) => {
let shape = null;
switch (type) {
case 'rectangle': {
shape = shapeRectangle(dimensions);
break;
}
case 'circle': {
shape = shapeCircle(dimensions);
break;
}
}
if (shape) {
shape = {
...shape,
...withSetFillColor(shape),
...withMoveBy(shape),
};
}
return shape;
};
let r = createShape('rectangle', {
x: 1,
y: 1,
width: 10,
height: 10,
});
let c = createShape('circle', { x: 10, y: 10, diameter: 10 });
r.moveBy(2, 3);
c.moveBy(1, 2);
r.setFillColor('red');
c.setFillColor('blue');
console.log(r);
console.log(c);
输出:
标记为// 1 的线在矩形和圆形的情况下打印white。
标记为// 2 的线条打印出red 用于矩形,blue 用于圆形。
最终输出为:
{
"type": "rectangle",
"fillColor": "white",
"dimensions": {
"x": 3,
"y": 4,
"width": 10,
"height": 10,
"fillColor": "red"
}
}
{
"type": "circle",
"fillColor": "white",
"dimensions": {
"x": 11,
"y": 12,
"diameter": 10,
"fillColor": "blue"
}
}
作为对象属性的fillColor仍然是white。
但是,dimensions 里面的那个值是正确的。
【问题讨论】:
-
您创建
shape,将其传递给withSetFillColor(),然后创建一个不同的shape对象。为简单起见,我们称之为shape2。因此,当您在shape2上调用withSetFillColor('red')时,只有shape1被更改。两个对象共享dimensions。
标签: javascript node.js function composition