首頁  >  文章  >  web前端  >  javascript利用apply和arguments重複使用方法_javascript技巧

javascript利用apply和arguments重複使用方法_javascript技巧

WBOY
WBOY原創
2016-05-16 17:12:301024瀏覽

首先,有個單例對象,它上面掛了很多靜態工具方法。其中有一個是each,用來遍歷數組或物件。

複製程式碼 程式碼如下:

var nativeForEachative = [].forforEachative> = [].map
var util = {
    each: function (obj, iterator, context) {
        nativeForEach) {
          obj.forEach(iterator, context)
        } else if ( i = 0; i                   } else {
            for (var k in obj) {
                    }
    },
    map: function(obj, iterator, context) {
        var results = []
     obj.map === nativeMap) return obj .map(iterator, context)     
        this.each(obj, function(val, i, coll) {
           })
        return results
    }
}




還有諸如every、some等對集合(Array,Hash)操作的工具函數。使用時採用util.xx方式。

如果定義了一個集合類,這個類別內部有集合資料。

複製程式碼

程式碼如下:

function Collection(data) { function Collection(data) { this. = data || []     // some other property     // this.xxx = yyy
}
Collection.prototype = {




可以很方便的把util上的方法拷貝到集合類別上,如


複製程式碼

程式碼如下:

function copyMethod(clazz, obj) {         clazz.prototype[method] = function() {            var target = this.data             args. unshift(target)             obj[method].apply(obj, args)        


這樣拷貝後,Collection的實例就有了util上的方法,util操作的集合物件(第一個參數)就是Collection的this.data。如下直接可以遍歷this.data了。





複製程式碼


程式碼如下:

var coll = new Collection([10, 20,300 ]) 

// 遍歷

coll.each(function(k) {

    console.log(k)

這個模式在許多開源函式庫中使用,像是jQuery,它的 $.each/$.map 很方便的拷貝到了 $().each/$().map。

又如Backbone,它的 _.each/_.map/_.every/_.chain (還有很多)都拷貝到了 Collection的原型上。

複製代碼 代碼如下:

// Underscore methods that thatweant to implement thatment .
// 90% of the core usefulness of Backbone Collections is actually implemented
// right here:
var methods = ['forEach', 'each', 'map', 'collect', ' reduce', 'foldl',
  'inject', 'reduceRight', 'foldr', 'find', 'detect', 'filter', 'select',
  'reject', 'every', ' all', 'some', 'any', 'include', 'contains', 'invoke',
  'max', 'min', 'toArray', 'size', 'first', 'head', 'take', 'initial', 'rest',
  'tail', 'drop', 'last', 'without', 'difference', 'indexOf', 'shuffle',
  'lastIndexOf', '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);
    args.unshift(this.models);
    return _fod ;
  }; });

又有,把 _.keys / _.values / _.pairs / _.invert / _.pick 等物件操作的實用方法拷貝了 Backbone.Model上 (1.0新增)

代碼如下:


var modelMethods = ['keys', 'values', 'pairs', 'invert', 'pick', 'omit'];

// Mix in each Underscore method as a proxy to `Model#attributes`.
_.each(modelMethods, function (method) {
  Model.prototype[method] = function() {
    var args = slice.call(arguments);
    args.unshift(this.attributs); ].apply(_, args);
  };
});

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn