Unexpected results with JS prototype inheritance

I have a base class:

Stage.js:

function Stage(name) {
  this.my_name = name;
}

Stage.prototype.name = function() {
  return this.my_name;
}

module.exports = Stage;

Parallel:

var Stage = require("./Stage");

ParallelStage.prototype = Stage.prototype;

ParallelStage.prototype.execute = function() {
  console.log("+++ Executing stage " + this.name()+ " in parallel...");
  return this;
}

function ParallelStage(name) {
  Stage.call(this,name);
  return this;
}

module.exports = ParallelStage;

and Serial.js:

var Stage = require("./Stage");

SerialStage.prototype = Stage.prototype;

SerialStage.prototype.execute = function() {
  console.log("+++ Executing stage " + this.name()+ " in serial...");
  return this;
}

function SerialStage(name) {
  Stage.call(this,name);
  return this;
}

module.exports = SerialStage;

However, when I run:

var Parallel = require ("./ParallelStage");
var Serial = require ("./SerialStage");

var parallel = new Parallel("Extraction");
parallel.execute();

I get the following output:

+++ Executing stage Extraction in serial...

I am clearly missing something fundamental in the inheritance of javascript and prototype. Can someone tell me what I'm missing here? I expected it to show the execution of the scene in parallel, and not serial ...

+4
source share
4 answers

For proper prototype inheritance you should use

var child.prototype = Object.create(parent.prototype, {...object with properties/methods...}

When you call

SerialStage.prototype = Stage.prototype;

SerialStage.prototype, Stage.prototype, .

ParallelStage.prototype = Object.create(Stage.prototype);

ParallelStage.prototype = Object.create(Stage.prototype);
0

serialStage ParallelStage Stage.prototype, .

- , , ,

var Stage = function Stage() {}

ParallelStage.prototype = Stage.prototype; // set to Stage.prototype
ParallelStage.prototype.execute = function() {} 
// ^ you've attached an "execute" method to the Stage.prototype object


SerialStage.prototype = Stage.prototype; // set to the same Stage.prototype
SerialStage.prototype.execute = function() {}
// ^ you've just overwritten the "execute" function in Stage.prototype

Object.create, Object.assign -, , sorta .

0

:

SerialStage.prototype = Stage.prototype;

- , , . ParallelStage SerialStage . execute, , .

:

ParallelStage.prototype = new Stage();

SerialStage.prototype = new Stage();

, . , .

0

, Stage :

ParallelStage.prototype = Stage.prototype

ParallelStage.prototype Stage.prototype. , Stage.

- , Serial.js Stage.js Parallel.js; Stage.prototype, Stage, SerialStage ParallelStage.

( ) :

Child.prototype = Object.create(Parent.prototype)

, , .

0

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


All Articles