From 1d65965a410165b8cd368dd641456b71b11ca821 Mon Sep 17 00:00:00 2001 From: AJ ONeal Date: Thu, 10 Nov 2011 11:21:18 -0700 Subject: [PATCH] added example with subtyping arrays --- javascript-fu/README.md | 8 ++++ javascript-fu/subclass-array.js | 82 +++++++++++++++++++++++++++++++++ 2 files changed, 90 insertions(+) create mode 100644 javascript-fu/README.md create mode 100644 javascript-fu/subclass-array.js diff --git a/javascript-fu/README.md b/javascript-fu/README.md new file mode 100644 index 0000000..9b8b5b2 --- /dev/null +++ b/javascript-fu/README.md @@ -0,0 +1,8 @@ +What NOT to do +=== + +These examples are for the purpose of explaining the stupid things people choose to do for idoitic reasons. + +There are also examples of things which are broken, but should have worked in a more ideal world. + +**NEVER USE THESE EXAMPLES IN REAL CODE** diff --git a/javascript-fu/subclass-array.js b/javascript-fu/subclass-array.js new file mode 100644 index 0000000..e322614 --- /dev/null +++ b/javascript-fu/subclass-array.js @@ -0,0 +1,82 @@ +// Adapted from http://dean.edwards.name/weblog/2006/11/hooray/ + +// Note: This examples works in browsers and SSJS. It won't work in MSIE. +(function () { + "use strict"; + + // create the constructor + function FileList(args) { + var i; + + if (!(args instanceof Array)) { + args = Array.prototype.slice.call(arguments); + } + + // forEach won't work because `this` loses its scope + for (i = 0; i < args.length; i += 1) { + this.push(args[i]); + } + + // prevent user extension + this.push = undefined; + this.pop = undefined; + }; + + // inherit from Array + FileList.prototype = new Array; + + // add some sugar + FileList.prototype.item = function(index) { + return this[index]; + }; + + // For some reason this won't stringify correctly + // as a subtype of Array + FileList.prototype.toJSON = function () { + return this.slice(); + }; + + FileList.prototype.toString = function () { + return JSON.stringify(this.join(',')); + }; + + module.exports = FileList; +}()); + + +// Test functionality of the above +(function () { + "use strict"; + + var FileList = module.exports + , fileList + ; + + // First of all: JavaScript doesn't have arrays. Really! + // http://javascript.about.com/od/problemsolving/a/notarrays.htm + + // NOTE: .length will only be correct if .push is used + // not if [i] notation is used + /* + var fileList = new FileList(); + fileList.push('a'); + fileList.push('b'); + fileList.push('c'); + */ + + fileList = new FileList(['a','b',3]); + console.error('[FAIL]', 'Array.isArray(fileList):', Array.isArray(fileList)); + + console.log(fileList.item(0)); + console.log(fileList[1]); + + fileList = new FileList('a','b',3); + console.log(fileList.item(2)); + + // Love the brokenness + console.log(JSON.stringify(['a', 'b', 3])); + //console.log(fileList.toString()); + console.log([1, 2, 3].toString()); + console.log(JSON.stringify(fileList), typeof JSON.stringify(fileList)); + console.log(fileList.forEach) +}());