Risk of using native Array prototype method on other objects?
I have made a lot of jQuery special events, and now I am trying to make them jQuery plugins.
My code is:
$.each("down move hold up tap swipeUp swipeDown swipeLeft swipeRight drag dragCell".split(" "), function(key, value) {
$.fn[value] = function() {
var args = [value].concat(Array.prototype.splice.call(arguments,0));
if ( $.isFunction(arguments[0]) || $.isFunction(arguments[1]) ) {
return this.bind.apply(this, args);
} else {
return this.trigger.apply(this, args);
}
};
});
Wher开发者_如何学编程e I loops an array of names (down, move, hold, up, etc...) and dynamically creates jQuery plugins.
As you can see a take the value and name the plugin after it: $.fn.down
, $.fn.move
, etc..
Then I take the arguments and loop it through a native array method.
Array.prototype.splice.call(arguments, 0);
This returns a native Array [arguments[0], arguments[1], ...]
And concat
it with the value
and ends up with:
["down", arguments[0], arguments[1], ...],
["move", arguments[0], arguments[1], ...],
....
Is there any risk of doing this (using native methods and other objects then meant), and is there any possibility of losing data?
As you can see it messes with jQuery's bind
and trigger
methods. Is this also dangerous?
Okay i close this question: A way to achieve the same for arguments is:
Thanks to raynos
var toArray = function (obj) {
var ret = new Array(obj.length);
for (var i = 0, len = obj.length; i < len; i++) {
ret[i] = obj[i];
}
return ret;
}
toArray(arguments);
精彩评论