Javascript reuse methods using apply and arguments

Source: Internet
Author: User

First, there is a singleton object with many static tool Methods mounted on it. One of them is each, which is used to traverse arrays or objects.

Copy codeThe Code is as follows:
Var nativeForEach = []. forEach
Var nativeMap = []. map
Var util = {
Each: function (obj, iterator, context ){
If (obj = null) return
If (nativeForEach & obj. forEach === nativeForEach ){
Obj. forEach (iterator, context)
} Else if (obj. length = + obj. length ){
For (var I = 0; I <obj. length; I ++ ){
If (iterator. call (obj [I] | context, obj [I], I, obj) = true) return
}
} Else {
For (var k in obj ){
If (iterator. call (obj [k] | context, obj [k], k, obj) = true) return
}
}
},
Map: function (obj, iterator, context ){
Var results = []
If (obj = null) return results
If (nativeMap & obj. map === nativeMap) return obj. map (iterator, context)
This. each (obj, function (val, I, coll ){
Results [I] = iterator. call (context, val, I, coll)
})
Return results
}
}

There are also tool functions such as every and some for set (Array, Hash) operations. Util. xx is used.

If a collection class is defined, this class contains set data.

Copy codeThe Code is as follows:
Function Collection (data ){
This. data = data | []
// Some other property
// This. xxx = yyy
}
Collection. prototype = {
// Some method
}

You can easily copy the methods on util to the Collection class, as shown in figure

Copy codeThe Code is as follows:
Function copyMethod (clazz, obj ){
For (var method in obj ){
Clazz. prototype [method] = function (){
Var args = []. slice. call (arguments)
Var target = this. data
Args. unshift (target)
Obj [method]. apply (obj, args)
}
}
}
CopyMethod (Collection, util)

In this way, the Collection instance has the util method. The Collection object (the first parameter) of the util operation is the this. data of the Collection. You can directly traverse this. data as follows.

Copy codeThe Code is as follows:
Var coll = new Collection ([10, 20, 30])

// Traverse
Coll. each (function (k ){
Console. log (k)
})

// Operation
Var arr = coll. map (function (k ){
Return k-5
})
Console. log (arr) // 5, 15, 25

This mode is used in many open-source libraries, such as jQuery. Its $. each/$. map can be easily copied to $ (). each/$ (). map.

Another example is Backbone. Its _. each/_. map/_. every/_. chain (and many more) are copied to the Collection prototype.

Copy codeThe Code is as follows:
// Underscore methods that we want to implement on the Collection.
// 90% of the core usefulness of Backbone Collections is actually implemented
// Right here:
Var methods = ['foreach', 'REACH', 'map', 'Collect ', 'reduce', 'foldl ',
'Inobject', 'certificate', 'foldr ', 'Find', 'detect ', 'filter', 'select ',
'Reobject', 'every', 'all', 'some', 'any', 'include ', 'Container', 'invoke ',
'Max ', 'Min', 'toarray', 'SIZE', 'First', 'head', 'Take ', 'initial', 'Rest ',
'Tail', 'drop', 'last', 'without', 'difference ', 'indexof', 'shuffle ',
'Lastdexof ', 'isempty', 'chain'];

// Mix in each Underscore method as a proxy to 'collection # models '.
_. Each (methods, function (method ){
Collection. prototype [method] = function (){
Var args = slice. call (arguments );
Args. unshift (this. models );
Return _ [method]. apply (_, args );
};
});

Also, we copied the practical methods for object operations such as _. keys/_. values/_. pairs/_. invert/_. pick to Backbone. Model (New in 1.0)

Copy codeThe Code is as follows:
Var modelMethods = ['keys ', 'values', 'pairs', 'invert', 'pick', 'omit '];

// Mix in each Underscore method as a proxy to 'model # bubutes '.
_. Each (modelMethods, function (method ){
Model. prototype [method] = function (){
Var args = slice. call (arguments );
Args. unshift (this. attributes );
Return _ [method]. apply (_, args );
};
});

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.