jQuery 深度克隆示例

jQuery 深度克隆示例

原文: https://howtodoinjava.com/jquery/jquery-deep-cloning-example/

jQuery 深度克隆意味着独立更改原始对象或克隆对象不会对其他对象产生影响。 换句话说,两个对象(原始对象和克隆对象)都彼此完全独立。 您可以在对象克隆的指南中阅读有关克隆的更多信息。

jquery_logo

使用方法:

var clonedObject = jQuery.extend({}, originalObject);

jQuery 深度克隆示例

在 jquery 克隆示例代码中,我创建了一个User对象并创建了两个属性,即名字和姓氏。 然后,我为这些属性创建了两个设置器函数,还使用了原型属性添加了另一种方法。

实际上,使用“extend”关键字的 jquery 克隆机制用于将两个或多个对象的属性和属性复制/合并到第三个或完全新的对象中。 可以在中找到更多详细信息。

示例代码如下所示:

//Create the object
var user = new User($("#fname").val(),$("#lname").val());
//Check the original object values
$("#origUser").html(user.getUserName());
//Cloning is done here
var cloned = $.extend({}, user);
//Change the firstname property
user.fname = 'Noname';
//Let's check the original and cloned object again
$("#origAfterUser").html(user.getUserName());
//Verify cloned is same as original in starting
$("#clonedUser").html(cloned.getUserName());

示例应用

<HTML>
	<HEAD>
		<TITLE> jQuery Cloning Example </TITLE>
		<script src=&quot;http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js&quot;></script>
		<SCRIPT LANGUAGE=&quot;JAVASCRIPT&quot;>
		var User = function(fname,lname){
			this.fname = fname,
			this.lname = lname,
			this.getFName = function(){
				return this.fname;
			},
			this.getLName = function(){
				return this.lname;
			}
		};
		User.prototype.getUserName = function() {
			return (this.getFName() + &quot; &quot; + this.getLName());
		}
		function cloneDemo(){
			//Create the object
			var user = new User($(&quot;#fname&quot;).val(),$(&quot;#lname&quot;).val());
			//Check the original object values
			$(&quot;#origUser&quot;).html(user.getUserName());
			//Cloning is done here
			var cloned = $.extend({}, user);
			//Change the firstname property
			user.fname = 'Noname';
			//Let's check the original and cloned object again
			$(&quot;#origAfterUser&quot;).html(user.getUserName());
			//Verify cloned is same as original in starting
			$(&quot;#clonedUser&quot;).html(cloned.getUserName());
		}
		</SCRIPT>
	</HEAD>
	<BODY>
		<h3>jQuery Cloning Example</h3>
		To clone an object, you can directly use clone() method.
		<p>
			First Name : <input type='text' id='fname'/>
		</p>
		<p>
			Last Name : <input type='text' id='lname'/>
		</p>
		<p>
			<input type='button' value='Create above User and Clone it' onclick=&quot;cloneDemo();&quot;/>
		</p>
		<p>I have changed the first name of orginal Object to 'Noname'</p>
		<p>
			Original User : <span id='origUser'></span>
		</p>
		<p>
			After Cloning Original User : <span id='origAfterUser'></span>
		</p>
		<p>
			Cloned User Still is : <span id='clonedUser'></span>
		</p>
	</BODY>
</HTML>

祝您学习愉快!