1

I have this code:

pPoint = function(x,y){
    this.x = x || 0;
    this.y = y || 0;
}

pPoint.prototype = {
    constructor:pPoint,
    add:function(){
        return this.x+this.y;
    }
}

And if I do:

a = new pPoint(10,20)
console.log(a.add());

Works as expected (returns 30).

However if I do this:

Array.prototype = {
    abcd:function(){
        console.log("bla bla testing");     
    }
}

And then do this:

b = new Array();
b.abcd();

It does not work... why?

I know that if I do this works fine...

Array.prototype.abcd:function(){
        console.log("bla bla testing");     
    }
}

I just dont get why the preivous one works on my pPoint and not in Array...

Fiddle: http://jsfiddle.net/paulocoelho/wBzhk/

1
  • Setting the prototype in this way (your first example pPoint.prototype={}) will have pPoint.prototype.constructor point to Object instead of pPoint. constructor should point to the right function, if you're not using it and you're not expecting other people to extend your code this should not be a problem though but it's worth mentioning. Commented Jul 23, 2013 at 5:53

1 Answer 1

5

The Array.prototype property is not writable.

Therefore, Array.prototype = ... has no effect.

You can see this by looking at Object.getOwnPropertyDescriptor(Array, 'prototype').writable, which is false.


Had you been able to do that, you would lose all of the built-in array methods, since they are properties of the standard Array.prototype and not of the new object you're trying to replace it with.

Sign up to request clarification or add additional context in comments.

2 Comments

Oh interesting. So by doing it that way I would be effectively rewriting anything that was set using the "prototype". Thanks! :)
Well, you'd potentially only loose methods for array instances created after the assignment. But that's moot since it can't be done anyway. :-/

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.