On Jul 20, 10:10 pm, Xavier MONTILLET <[email protected]> wrote:
> Oh. Never thought if that...
>
> When i implement constructors that are lists somehow, i do this :
>
> function Constructor( array ) {
> Array.prototype.splice.apply( this, [ 0, 0 ].concat( array ) );
> }
There are a few issus with that, clearly there is code missing. Can
you explain what it should do?
> Constructor.prototype = Object.create( Array.prototype );
How is that different to:
Constructor.prototype = Array.prototype;
other than that the former inserts an extra empty object on the
inheritance chain. I suppose it can be used to add methods to
Constructor.prototype without affecting Array.prototype. The following
can also be used:
var constProto = [];
constProto.method = ...
...
Constructor.prototype = constProto;
If the extra object is needed, then a clone or beget function can be
used if Object.create is not available.
> But i don't get the same behavior with the length...
Because the length property of an array is special, in many browsers
only objects created by the Array constructor have that special length
property. Recent versions of Firefox and Chrome (and maybe others) are
more generic and the following "works":
function Bar(){}
Bar.prototype = Array.prototype;
bar = new Bar();
alert(bar.slice); // function, ok
alert(bar.length); // 0, good
bar.push('zero');
alert(bar.length); // 1, looking even better
But in IE, length will be zero still.
var x = bar.slice();
alert(x[0]); // zero
alert(Object.prototype.toString.call(x)); // [object Array]
alert(Object.prototype.toString.call(bar)); // [object Object]
Equivalent to:
alert(Array.isArray(x)); // true
alert(Array.isArray(bar)); // false
--
Rob
--
To view archived discussions from the original JSMentors Mailman list:
http://www.mail-archive.com/[email protected]/
To search via a non-Google archive, visit here:
http://www.mail-archive.com/[email protected]/
To unsubscribe from this group, send email to
[email protected]