0
var a=[1,2,3,4]

function Demo(){}

Array.prototype={
  foo:function(){
    alert(1)
  }
}//a.foo is not a function

Array.prototype.foo=function(){
  alert(1)
}//alert(1)

a.foo()

Demo.prototype={
  foo:function(){
    alert(1)
  }
}

var b=new Demo()
b.foo()//alert(1)

Why can't Array add prototype with literals? Also, why does it work when I use a constructor?

Here is an example: https://jsbin.com/zowalu/edit?js,console

0

1 Answer 1

2

You cannot replace the Array.prototype object (which is what you are trying to do in the first example), as Array.prototype is read-only.

Your second example works because you are simply adding a key to the prototype, not replacing it.

The third example works, because Demo is an object of your design, whereby the prototype is not read-only.

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

2 Comments

Thanks,i know,you mean i try to replace all in first example
Even if the first case worked, a is constructed before the replacement of Array.prototype so would still reference the original prototype anyway.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.