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

I am learning JavaScript and found two ways to assign a prototype.

First A.prototype = B.prototypeand secondA.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 a difference and which way to prefer?
  • Is there any other way to assign a prototype?

Update:

According to Felix Kling, there is a third way to designate a prototype:

A.prototype = Object.create(B.prototype);
+4
source share
3 answers

This is just another method.

A.prototype = B.prototype;

Thus, any changes to the prototype Bwill also change the prototype A, because they are the same object, and one that should have undesirable side effects.

 A.prototype = new B();

Using this, we also perform inheritance with prototypes.

A a B, A B.

# 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' 

:

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
+2

- B, :

function A() {
  console.log("A!")
}

function B() {
  this.text = "aaa";
}

:

// First case
A.prototype = B.prototype;
a = new A();  

// a --> {}


// Second case
A.prototype = new B();
a = new A();  // a instanceof A,B

// a --> { text="aaa" }
+1

@ Yaroslav Karandashev, the difference in one case is you inherit only functionality

A.prototype = B.prototype;

Otherwise, you inherit both state and functionality.

A.prototype = new B();

You can modify the first case a bit to have the same behavior:

// First case
function B() {
  console.log("B!")
}
//child:
function A() {
  console.log("A!")
  //invoke parent constructor:
  B.apply(this);
}

A.prototype = B.prototype;
a = new A();  // a instanceof A,B


// Second case
function B() {
  console.log("B!")
}
//child, you do not need to invoke constructor of base class:
function A() {
  console.log("A!")
}
//base class constructor is invoked here:
A.prototype = new B();
a = new A();  // a instanceof A,B
0
source

Source: https://habr.com/ru/post/1525171/


All Articles