jQuery深度克隆示例

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

jquery_logo

使用方法:

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

jQuery深度克隆示例

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

实际上,使用’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());

应用范例

[su_tabs]
[su_tab title =“演示”]

[/ su_tab]
[su_tab title =“源代码”]

<HTML>
	<HEAD>
		<TITLE> jQuery Cloning Example </TITLE>
		<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
		<SCRIPT LANGUAGE="JAVASCRIPT">
		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() + " " + this.getLName());
		}
		function cloneDemo(){
			//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());
		}
		</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="cloneDemo();"/>
		</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>

[/ su_tab]
[/ su_tabs]

学习愉快!

saigon has written 1440 articles

Leave a Reply