我正在为这个jQuery表达式寻找替代的等效解决方案:
$.extend(true, {}, {foo: "bar"}, {bar: "foo"});
我正在使用Babel和ES_2015以及polyfill。现在我假设,可以使用
Object.assign({}, {foo: "bar"}, {bar: "foo"});
在我的情况下,这不是我想要的,正如我发现的那样,当一个属性是我自己的类时,这不起作用。
例如
let a = {origin: new Point(0,0), sizes: new Point(100, 100)};
let b = {origin: new Point(50,50), sizes: new Point(200, 200)};
Object.assign({}, a, b);
它不会复制我的Point类。有没有其他解决方案,让jQuery离开?
致以最诚挚的问候,
迈克尔
编辑2:Bergi是对的,我自己也很困惑。我会做一些测试,但现在它看起来很好。也许我的代码中的其他地方有更大的问题。会回复你。至今为止人们 编辑,所以没有人感到困惑:
我需要Point的一个实例。不是一个对象。
/*global Point*/
describe('Object.assign', function() {
"use strict";
it("Point", function() {
let a = {
origin: new Point.Point(0, 0),
sizes: {
x: new Point.Point(100, 100),
y: new Point.Point(500, 500)
}
};
let b = {
origin: new Point.Point(50, 50),
sizes: {
x: new Point.Point(1000, 1000),
y: new Point.Point(5000, 5000)
}
};
var s = Object.assign({}, a, b);
console.log(typeof s.origin, s.origin instanceof Point.Point);
console.log(typeof s.sizes.x, s.sizes.x instanceof Point.Point);
console.log(typeof s.sizes.y, s.sizes.y instanceof Point.Point);
console.log(s.sizes.y.clone, s.sizes.x.clone);
});
});
所以最后,我想要一个Point的实例是真的;)
答案 0 :(得分:2)
我认为,它需要实施"克隆"方法。但ES2015没有这种方法...
(jQuery有克隆方法,但我知道你不想使用它......)
我的实现如下,请将其用于您的实施:)
function clone(obj) {
if (null == obj || "object" != typeof obj) return obj;
var copy = new obj.constructor;
for (var attr in obj) {
if (obj.hasOwnProperty(attr)) {
if (null == obj[attr] || "object" != typeof obj[attr]) {
copy[attr] = obj[attr];
} else {
copy[attr] = clone(obj[attr]);
}
}
}
return copy;
}
class Point {
constructor(x, y) {
this.x = x;
this.y = y;
}
}
let a = {origin: new Point(0,0), sizes: new Point(100, 100)};
let b = {origin: new Point(50,50), sizes: new Point(200, 200)};
const copied = Object.assign({}, clone(a), clone(b)); // <- copied!
console.log(copied); // { origin: Point { x: 50, y: 50 }, sizes: Point { x: 200, y: 200 } }
b.origin.x = 300; // <- changed!
console.log(b); // { origin: Point { x: 300, y: 50 }, sizes: Point { x: 200, y: 200 } } (b was changed)
console.log(copied); // { origin: Point { x: 50, y: 50 }, sizes: Point { x: 200, y: 200 } } (but, copied isn't changed!)
&#13;