What is the difference between A.prototype = B.prototype and A.prototype = new B()?

javascript, new-operator, prototype

Solution

It's just another technique.

A.prototype = B.prototype;

By doing this, any changes to the `B` prototype will also change the `A` prototype because they’re the same object, and that’s bound to have undesirable side effects.

 A.prototype = new B();

Using this , we're ALSO Achieving inheritance with prototypes.

We make a `A` a `B` by making the `A` prototype an instance of `B`.

Example #1 :

function A() {  console.log("A!")}
function B() {  console.log("B!")}
A.prototype = new B();
a = new A();    
B.bb=function (){alert('');}
console.log(a.bb()) //Uncaught TypeError: Object #<B> has no method 'bb' 

now look at this :

function A() {  console.log("A!")}
function B() {  console.log("B!")}
A.prototype = B.prototype;
a = new A();    
B.prototype.bb=function (){alert('');}
console.log(a.bb()) //does alert

Problem

I am learning JavaScript and found two ways of assigning prototype. The first is `A.prototype = B.prototype` and the second is `A.prototype = new B()` For example: ``` function A() { console.log("A!") } function B() { console.log("B!") } // First case A.prototype = B.prototype; a = new A(); // a instanceof A,B // Second case A.prototype = new B(); a = new A(); // a instanceof A,B ``` - Is there any difference and which way to prefer? - Is there any other way to assign prototype? Update: As Felix Kling advised there is a third way to assign a prototype: ``` A.prototype = Object.create(B.prototype); ```

Original source

Related problems