Created
July 6, 2011 03:47
-
-
Save eliperelman/1066518 to your computer and use it in GitHub Desktop.
Unlimited arguments
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Antipattern: | |
var preload = function (path) { | |
var img = new Image(); | |
img.src = path; | |
}; | |
preload('apple.png'); | |
preload('banana.png'); | |
preload('cheese.png'); | |
preload('donut.png'); | |
preload('egg.png'); | |
preload('fish.png'); | |
// Good pattern: | |
var preload = function () { | |
var args = Array.prototype.slice.call(arguments), | |
img; | |
for (var i = 0; i < args.length; i++) { | |
img = new Image(); | |
img.src = args[i]; | |
} | |
}; | |
preload('apple.png', 'banana.png', 'cheese.png', 'donut.png', 'egg.png', 'fish.png'); | |
// Alternate pattern: | |
var preload = function () { | |
var args = Array.prototype.slice.call(arguments), | |
img; | |
for (var i = 0; i < args.length; i++) { | |
img = new Image(); | |
img.src = args[i]; | |
} | |
}; | |
var args = [ 'apple.png', 'banana.png', 'cheese.png', 'donut.png', 'egg.png', 'fish.png' ]; | |
preload.apply(args); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You can omit the slice.call - arguments has a length and can be iterated like an array (only without its methods). Since the Image Object is not needed furthermore, you can use it anonymously: