자바 스크립트 객체를 복제하는 방법이 있습니까? DOM 요소가 아니라 특정 생성자가있는 객체입니다. 예를 들어 전화 번호 개체가 있다고 가정 해 보겠습니다.복제/복제 자바 객체
function PhoneNumber(number, type) {
this.number = number;
this.type = type;
}
var phoneObj1 = new PhoneNumber('1111111111', 'Home');
var phoneObj2 = //Copy of phoneObj1, but unique so I can set other parameters if necessary.
jQuery는이 문제를 연장하여 해결합니다. 대신 전화 번호 생성자 이름의
Object{number:'1111111111' type:'Home'}
:
var phoneObj2 = $.extend({}, phoneObj1);
는하지만 일반 객체를 반환합니다. 확장자에 실제로 새로운 PhoneNumber()를 작성하지 않고 원래 phoneObj1의 생성자를 전달하는 방법이 필요합니다. 왜냐하면이 코드가 사용되는 코드가 많은 다른 유형의 객체에서 사용되므로 정확한 시간을 알지 못하기 때문입니다. 내가 참조 할 객체가 있다는 사실을 제외하고는 사용해야하는 생성자.
var phoneObj2 = $.extend(new PhoneNumber(), phoneObj1); //I CANNOT do this!
//Maybe something like this?
var phoneObj2 = $.extend(new phoneObj1.constructor.name, phoneObj1); //This throws an error.
가능한 중복 (HTTP : // 유래.com/questions/122102/what-is-the-the-most-efficient-way-to-clone-a-javascript-object) – fyr
몇 가지 좋은 해답은 http://stackoverflow.com/questions/332422/how-do-i -get-the-object-type-in-javascript – georg
은 'fyr'과 동의했습니다. 나는이 방법을 가장 직선적 인 방법으로 사용한다. Object.create (obj); – dbrin