Skip to content

Instantly share code, notes, and snippets.

@rwaldron
Forked from dherman/from.js
Created November 18, 2011 16:56
Show Gist options
  • Save rwaldron/1377030 to your computer and use it in GitHub Desktop.
Save rwaldron/1377030 to your computer and use it in GitHub Desktop.
possible meanings of Array.from
Array.from = function from(x) {
var result = new Array();
for (var i = 0, n = x.length; i < n; i++) {
if (i in x)
result[i] = x[i];
}
return result;
};
// If Object.getPrototypeOf(Subarray) === Array, then:
// !(Subarray.from([1,2,3]) instanceof Subarray)
Array.from = function from(x) {
var result = new this();
for (var i = 0, n = x.length; i < n; i++) {
if (i in x)
result[i] = x[i];
}
return result;
};
// If Object.getPrototypeOf(Subarray) === Array, then:
// Subarray.from([1,2,3]) instanceof Subarray
// But extracting Array.from requires bind.
// And this assumes that all subclasses of Array will have a zero-argument constructor.
Array.from = function from(x) {
var result = new (this || Array)();
for (var i = 0, n = x.length; i < n; i++) {
if (i in x)
result[i] = x[i];
}
return result;
};
// If Object.getPrototypeOf(Subarray) === Array, then:
// Subarray.from([1,2,3]) instanceof Subarray
// Extracting Array.from provides a sort of soft binding to Array.
// But extracting Subarray.from provides a soft binding to Array.
// Open questions:
// - many existing constructors in the stdlib do not inherit from their supertype
// constructor, but should classes do this?
// - if so, how should class factory methods like Array.from behave when inherited?
// - can an inheritable class factory method always assume subclasses will have
// constructors that can be called in an identical way?
// - should class factory methods be extractable without bind?
// - or should we have a more convenient syntax for bind? à la:
// http://wiki.ecmascript.org/doku.php?id=strawman:bind_operator
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment