Вопрос

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
  1. Is there any difference and which way to prefer?
  2. 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);
Это было полезно?

Решение

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

Другие советы

You can try to add something to B and you'll get the difference:

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

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

You will have:

// 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" }

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

A.prototype = B.prototype;

In another case you inherit both, state and functionality.

A.prototype = new B();

You may change slightly the first case, in order to have the same behavour:

// 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
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top