阅读关于'mixins'的书“YDKJS”(手动将一个对象复制到另一个对象中)我遇到了这样的说法:即使在复制之后,这两个对象仍然会有一些微妙的方式相互影响,例如如果它们共享对公共对象(例如数组或函数)的引用。 所以我需要一个这个陈述的例子。当我尝试更改公共对象(引用它)时它不起作用,它们不会相互影响。
function foo() {
let array = [2, 2, 1];
return array;
}
function mixin(sourceObj, targetObj) {
for (let key in sourceObj) {
if (!(key in targetObj)) {
targetObj[key] = sourceObj[key];
}
}
return targetObj;
}
const Vehicle = {
engines: 1,
fooo: foo,
ignition: function () {
console.log('Turning on my engine');
},
drive: function () {
this.ignition();
console.log('Steering and moving forward');
}
};
const Car = mixin(Vehicle, {
wheels: 4,
drive: function () {
console.log('Rolling on all ' + this.wheels + ' whells!');
}
});
console.log(Vehicle.fooo());
console.log(Car.fooo());
Car.fooo = function () {
let array = [34, 65, 1];
return array;
};
console.log(Car.fooo());
console.log(Vehicle.fooo());