1)普通函数实现
function cloneObject(obj) { if (obj === null || typeof obj !== ‘object‘) { return obj; } var temp = obj.constructor(); // give temp the original obj‘s constructor for (var key in obj) { temp[key] = cloneObject(obj[key]); } return temp; } var bob = { name: "Bob", age: 32 }; var bill = cloneObject(bob); bill.name = "Bill"; console.log(bob); console.log(bill);
2)通过json方法实现
var bob = { name: "Bob", age: 32 }; var bill = (JSON.parse(JSON.stringify(bob))); bill.name = "Bill"; console.log(bob); console.log(bill);
3)jquery中的$.extend
var bob = { name: "Bob", age: 32 }; var bill = $.extend(true, {}, bob); bill.name = "Bill"; console.log(bob); console.log(bill);
时间: 2024-09-28 20:11:30