jquery的-extend函數

js的淺拷貝與深拷貝:javascript

淺拷貝:JS中引用類型使用等號「=」 賦值,至關於把原來對象的地址拷貝一份給新的對象,這樣原來舊的對象與新的對象就指向同一個地址,改變其中一個對象就會影響另外那個對象,也就是所謂的淺拷貝。html

深拷貝:所謂」深拷貝」,就是可以實現真正意義上的數組和對象的拷貝。它的實現並不難,只要遞歸調用」淺拷貝」就好了。指向不一樣的地址。java

3.代碼示例:http://api.jquery.com/jQuery.extend/#jQuery-extend-target-object1-objectNjquery

<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery.extend demo</title>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
 
<div id="log"></div>
 
<script>
var object1 = {
apple: 0,
banana: { weight: 52, price: 100 },
cherry: 97
};
var object2 = {
banana: { price: 200 },
durian: 100
};
 
// Merge object2 into object1
$.extend( object1, object2 );
 
// Assuming JSON.stringify - not available in IE<8
$( "#log" ).append( JSON.stringify( object1 ) );
</script>
 
</body>
</html>
 
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery.extend demo</title>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
 
<div id="log"></div>
 
<script>
var object1 = {
apple: 0,
banana: { weight: 52, price: 100 },
cherry: 97
};
var object2 = {
banana: { price: 200 },
durian: 100
};
 
// Merge object2 into object1, recursively
$.extend( true, object1, object2 );
 
// Assuming JSON.stringify - not available in IE<8
$( "#log" ).append( JSON.stringify( object1 ) );
</script>
 
</body>
</html>
 
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery.extend demo</title>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
 
<div id="log"></div>
 
<script>
var defaults = { validate: false, limit: 5, name: "foo" };
var options = { validate: true, name: "bar" };
 
// Merge defaults and options, without modifying defaults
var settings = $.extend( {}, defaults, options );
 
// Assuming JSON.stringify - not available in IE<8
$( "#log" ).append( "<div><b>defaults -- </b>" + JSON.stringify( defaults ) + "</div>" );
$( "#log" ).append( "<div><b>options -- </b>" + JSON.stringify( options ) + "</div>" );
$( "#log" ).append( "<div><b>settings -- </b>" + JSON.stringify( settings ) + "</div>" );
</script>
 
</body>
</html>

3.源碼api

相關文章
相關標籤/搜索