Skip to content

Instantly share code, notes, and snippets.

@dherman
Created November 18, 2011 15:23
Show Gist options
  • Save dherman/1376730 to your computer and use it in GitHub Desktop.
Save dherman/1376730 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
@rwaldron
Copy link

In cases like Array.prototype.concat ( http://es5.github.com/#x15.4.4.4 ), what will occur in Step 2 if Subclass.prototype.concat?

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