Monday, November 4, 2013

Having fun with Function.prototype.call

var topics = ["idea","examples","post some code"];
//["idea","examples","post some code"]
topics.shift();
//"idea"
view raw gistfile1.js hosted with ❤ by GitHub

In javascript, using the .call() method allows you to specify the context of whatever object you pass to it. This allows you to call a string method from an array context, and vice versa.

topics.shift();
//"examples"
view raw gistfile1.js hosted with ❤ by GitHub

Check out the following script...

var arrayObject = ["What", "is", "going", 0,"on", 111,"..", "here"];
String.prototype.slice.call(arrayObject);
//"What,is,going,0,on,111,..,here"
String.prototype.concat.call(arrayObject);
//"What,is,going,0,on,111,..,here"
String.prototype.substring.call(arrayObject,1,10)
//"hat,is,go"
String.prototype.indexOf.call(arrayObject, "n,111")
//17
var stringObject = "Hello";
Array.prototype.forEach.call(stringObject, function(item){console.log(item)})
//H
//e
//l
//l
//o
Array.prototype.map.call(stringObject, function(item){
if( item >= "A" && item <= "Z")
return"U";
return "L"
})
//["U", "L", "L", "L", "L"]
//Upper and lowercase map for the string!
view raw gistfile1.js hosted with ❤ by GitHub

In all honesty, it may not be a good idea to use these methods, because they aren't supported on these objects, but check out what happens!

topics.shift();
//"post some code"
view raw gistfile1.js hosted with ❤ by GitHub

Go nuts and try out some other methods and post them in the comments to see what you come up with.

No comments:

Post a Comment