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));
運行結果:
Text代碼
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"}}
執行個體二:var r = angular.extend(b, a, z);相繼將對象a、z的第一層屬性(不管是簡單屬性還是對象)拷貝賦給對象b的第一層屬性,即如果是對象,則是引用的是同一個對象,並返回對象b
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));
運行結果:
Text代碼
a:{"name":"bijian","address":"shenzhen","family":{"num":6,"amount":"80W"}} b:{"name":"bijian","address":"shenzhen","family":{"amount":"150W","mainSource":"經營公司"}} r:{"name":"bijian","address":"shenzhen","family":{"amount":"150W","mainSource":"經營公司"}} a:{"name":"bijian","address":"shenzhen","family":{"num":6,"amount":"80W"}} b:{"name":"bijian","address":"hanzhou","family":{"amount":"180W","mainSource":"經營公司"}} r:{"name":"bijian","address":"hanzhou","family":{"amount":"180W","mainSource":"經營公司"}}
再多的執行個體也不如原始碼來的簡單、直接和準確,angular.extend源碼如下:
Js代碼
/** * @ngdoc function * @name angular.extend * @function * * @description * Extends the destination object `dst` by copying all of the properties from the `src` object(s) * to `dst`. You can specify multiple `src` objects. * * @param {Object} dst Destination object. * @param {...Object} src Source object(s). * @returns {Object} Reference to `dst`. */ function extend(dst) { var h = dst.$$hashKey; forEach(arguments, function(obj){ if (obj !== dst) { forEach(obj, function(value, key){ dst[key] = value; }); } }); setHashKey(dst,h); return dst; }
感謝閱讀,希望能協助到大家,謝謝大家對本站的支援!