[英]JS Object.assign with own classes as properties
我正在为此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吗?
最好的祝福,
迈克尔
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);
});
});
所以最后,我希望Point的instanceof为true;)
我认为,它需要实现“克隆”方法。但是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!)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.