New MooTools Methods: .from()
MooTools 1.3 beta 2 was recently released and you may see a few new methods implemented to String, Array, Number, and Function: from. The from method of each of those Types returns an object of that type. Simply put: you'll always receive back an object of that type based on what you give it.
The New Method Code
Function.from = function(item){
return (typeOf(item) == 'function') ? item : function(){
return item;
};
};
Array.from = function(item){
if (item == null) return [];
return (Type.isEnumerable(item) && typeof item != 'string') ? (typeOf(item) == 'array') ? item : Array.prototype.slice.call(item) : [item];
};
Number.from = function(item){
var number = parseFloat(item);
return isFinite(number) ? number : null;
};
String.from = function(item){
return item + '';
};
The from method is added to String, Array, Number, and Function natives. Enough with the underlying code though -- examples are easier to understand.
Function.from, Array.from, Number.from, String.from Examples
Array.from('Item');
//returns ['Item'] (array type)
Function.from('Item, Whoa, Hey');
//returns function() { return 'Item, Whoa', Hey'; } (function type)
String.from(function() { alert('MooTools FTW!'); });
//returns function () { alert("MooTools FTW!"); } (string type)
Number.from('8765309');
//returns 8765309 (number type)
Each example above shows you what's returned by each method. Being able to generate a given object type from any argument using from can save you a lot of time -- especially when a given MooTools class or method requires an argument of a specific type. from is just another example of how MooTools can make your JavaScript life easier!




Oh great! :)
nomore switch-cases for specific type argument…
Life is really easier with MooTools