我正在为这个 jQuery 表达式寻找一个替代的等效解决方案:
$.extend(true, {}, {foo: "bar"}, {bar: "foo"});
我正在使用带有 ES_2015 和 polyfill 的 Babel。现在我假设,可以使用
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,还有其他解决方案吗?
最好的问候,
迈克尔
edit2: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);
});
});
所以最后,我希望 s instanceof Point 为真 ;)
最佳答案
我想,它需要实现“克隆”方法。但是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!)
关于javascript - JS Object.assign 以自己的类作为属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37642273/