Skip to content

Instantly share code, notes, and snippets.

@rxaviers
Created May 15, 2013 21:49
Show Gist options
  • Select an option

  • Save rxaviers/5587698 to your computer and use it in GitHub Desktop.

Select an option

Save rxaviers/5587698 to your computer and use it in GitHub Desktop.
function Files() {
var array = [];
array.push.apply( array, arguments );
array.__proto__ = Files.prototype;
return array;
}
Files.prototype = [];
Files.prototype.into = function() {
return this[ this.length - 1 ];
};
@rwaldron
Copy link

function Files() {
  // A close approximation to a "super" call
  Array.call(this);

  this.push.apply(this, arguments);
}

// Assign Files.prototype to a new object
// created from Array.prototype
Files.prototype = Object.create(Array.prototype);

// Restore the constructor, as it was lost
// when we paved over Files.prototype in the previous
// operation
Files.prototype.constructor = Files;

// Define additional methods for Files objects
Files.prototype.into = function() {
  return this[ this.length - 1 ];
};

// examples

var files = new Files("a.js", "b.js");

console.log( files );
// ["a.js", "b.js"]

console.log( files.length );
// 2

files.push("c.js");

console.log( files );
// ["a.js", "b.js", "c.js"]

console.log( files.length );
// 3


// "length" gotchas...

files.length = 0;

console.log( files.length );
// 0

console.log( files );
// ["a.js", "b.js", "c.js"] uh oh...

// This is bad, as it becomes an exando property!!
files[10] = "d.js";

console.log( files.length );
// 0

console.log( files );
// Looks more like this now:
// { '0': 'a.js', '1': 'b.js', '2': 'c.js', '10': 'd.js', length: 0 }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment