Created
August 25, 2011 08:49
-
-
Save abozhilov/1170259 to your computer and use it in GitHub Desktop.
Array.prototype.toString - ECMAScript5
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
// In ECMA-262 5th edition all methods of Array.prototype are intentionally generic. It means if you pass different | |
// native object than array for the this value, the particular method will work in same way as for array instances. | |
// ECMA-262 does not define how those methods will work if you pass a host object for the this value. That behavior // is implementation dependent. | |
// For example: | |
var arr = []; | |
Array.prototype.push.call(arr, 1, 2); | |
arr[0]; //1 | |
arr[1]; //2 | |
arr.length; //2 | |
// If you repeat the above operations with: | |
var obj = {}; | |
Array.prototype.push.call(obj, 1, 2); | |
// The results will be absolutely the same as for array object. | |
Array.prototype.push.call(alert); //Unknown result - implementation dependent | |
// In ECMA-262 3rd edition the things were a little bit different. The methods `toString' and `toLocaleString' were // not intentionally generic. If you passed different object than array the method raised a TypeError. | |
// ECMA-262-3 environment: | |
Array.prototype.toString.call({}); //TypeError | |
// In ECMAScript3 environment the result `Array.prototype.toString' is same as calling `Array.prototype.join' with no | |
// separator. | |
// In ECMAScript5 the `Array.prototype.toString' is intentionally generic. Also it uses `join' method of its this | |
// value only if `join' is a method. If the `join' property does not have a callable value it is going to be used | |
// `Object.prototype.toString' instead. | |
var arr = [1, 2, 3]; | |
arr.toString(); // "1,2,3" | |
arr.join = null; // make join property not callable | |
arr.toString(); //[object Array] same as Object.prototype.toString.call(arr); | |
// While `Array.prototype.toString' is generic and use `join' method of its this value you are able to use your own | |
// `join'. | |
// For example: | |
var obj = { | |
join : function () { | |
return "Yo, I'm custom join nigga!" | |
} | |
}; | |
Array.prototype.toString.call(obj); // "Yo, I'm custom join nigga!" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment