gpt4 book ai didi

javascript - 在javascript中精确克隆一个对象

转载 作者:行者123 更新时间:2023-12-03 21:46:27 24 4
gpt4 key购买 nike

我尝试在 JavaScript 中精确克隆一个对象。我知道使用 jquery 的以下解决方案:

var newObject = jQuery.extend({}, oldObject);
// Or
var newObject = jQuery.extend(true, {}, oldObject);

但问题是,对象类型会丢失:

var MyClass = function(param1, param2) {
alert(param1.a + param2.a);
};
var myObj = new MyClass({a: 1},{a: 2});
var myObjClone = jQuery.extend(true, {}, myObj);
alert(myObj instanceof MyClass); // => true
alert(myObjClone instanceof MyClass); // => false

有什么解决方案可以让第二个警报变为真吗?

最佳答案

jQuery.extend 并不期望您使用instanceof 运算符。它正在做一个极其复杂的复制品,而不是真正的克隆。循环遍历元素是不够的。另外,调用构造函数并不是最好的方法,因为您会丢失参数。试试这个:

var MyClass = function(param1, param2) {
alert(param1.a + param2.a);
this.p1 = param1;
this.p2 = param2;
};

function Clone() { }
function clone(obj) {
Clone.prototype = obj;
return new Clone();
}

var myObj = new MyClass({a: 1},{a: 2});
var myObjClone = clone(myObj);
alert(myObj instanceof MyClass); // => true
alert(myObjClone instanceof MyClass); // => true
console.log(myObj); //note they are
console.log(myObjClone) //exactly the same

请注意,由于您的原型(prototype)现在指向原始 (myObj),因此对 myObj 的任何更改都将反射(reflect)在 myObjClone 中。 Javascript 的原型(prototype)继承有点棘手。您需要确保您的新对象具有正确的原型(prototype),因此具有正确的构造函数。

不可否认,Javascript 让我头疼。不过,我认为我读得对,来自 ECMAScript language spec :

13.2.2 [[Construct]]
When the [[Construct]] internal method for a Function object F is called with a possibly empty list of arguments, the following steps are taken:

  1. Let obj be a newly created native ECMAScript object.
  2. Set all the internal methods of obj as specified in 8.12.
  3. Set the [[Class]] internal property of obj to "Object".
  4. Set the [[Extensible]] internal property of obj to true.
  5. Let proto be the value of calling the [[Get]] internal property of F with argument >"prototype".
  6. If Type(proto) is Object, set the [[Prototype]] internal property of obj to proto.
  7. If Type(proto) is not Object, set the [[Prototype]] internal property of obj to the >standard built-in Object prototype object as described in 15.2.4.
  8. Let result be the result of calling the [[Call]] internal property of F, providing >obj as the this value and providing the argument list passed into [[Construct]] as args.
  9. If Type(result) is Object then return result.
  10. Return obj.

This person似乎比我更好地理解这个概念。 K,我现在要回到 java,在那里我游泳的次数比下沉的次数多:) 。

关于javascript - 在javascript中精确克隆一个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2261247/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com