AngularJS extend用法
angular.extend:依序將第二個參數及後續的參數的第一層屬性(不管是簡單屬性還是物件)拷貝賦給第一個參數的第一層屬性,即如果是物件,則是引用的是同一個對象,並傳回第一個參數對象。
實例一:var r = angular.extend(b, a);將物件a的第一層屬性(不管是簡單屬性或物件)拷貝賦給物件b的第一層屬性,即如果是對象,則是被引用的是同一對象,並回傳對象b
Js代碼
var a = { name : 'bijian', address : 'shenzhen', family : { num : 6, amount : '80W' } }; var b = {}; var r = angular.extend(b, a); console.log('a:' + JSON.stringify(a)); console.log('b:' + JSON.stringify(b)); console.log('r:' + JSON.stringify(r)); b.address = 'hanzhou'; b.family.amount = '180W'; console.log('a:' + JSON.stringify(a)); console.log('b:' + JSON.stringify(b)); console.log('r:' + JSON.stringify(r));
運作結果:
實例二:var r = angular.extend( b, a, z);相繼將物件a、z的第一層屬性(不管是簡單屬性或物件)拷貝賦給物件b的第一層屬性,即如果是對象,則是引用的是同一個對象,並回傳物件b
a:{"name":"bijian","address":"shenzhen","family":{"num":6,"amount":"80W"}} b:{"name":"bijian","address":"shenzhen","family":{"num":6,"amount":"80W"}} r:{"name":"bijian","address":"shenzhen","family":{"num":6,"amount":"80W"}} a:{"name":"bijian","address":"shenzhen","family":{"num":6,"amount":"180W"}} b:{"name":"bijian","address":"hanzhou","family":{"num":6,"amount":"180W"}} r:{"name":"bijian","address":"hanzhou","family":{"num":6,"amount":"180W"}}
運作結果:
實例也不如原始碼來的簡單、直接和準確,angular. extend原始碼如下:
Js程式碼var a = { name : 'bijian', address : 'shenzhen', family : { num : 6, amount : '80W' } }; var z = { family : { amount : '150W', mainSource : '经营公司' } }; var b = {}; var r = angular.extend(b, a, z); console.log('a:' + JSON.stringify(a)); console.log('b:' + JSON.stringify(b)); console.log('r:' + JSON.stringify(r)); b.address = 'hanzhou'; b.family.amount = '180W'; console.log('a:' + JSON.stringify(a)); console.log('b:' + JSON.stringify(b)); console.log('r:' + JSON.stringify(r));