kunquan
kunquan

Reputation: 1267

'this' keyword in Javascript inheritence chain

I have a function named Car as a supertype

let Car = function(){};
Car.prototype = {
    constructor: Car,
    numWheel: 4,
    numLight : 2,
    describe = function () {
        console.log(`This car is ${this.name} produced in ${this.version} `);
    }
}

I want to make a subtype constructor inherit from it, and make an instance from this constructor

let Honda = function (name, version) {
    this.name = name;
    this.version = version;
}
Honda.prototype = Object.create(Car.prototype);
Honda.prototype = {
    constructor: Honda
}
let civic = new Honda('civic', 2015);

The question i want to make is where the 'this' in supertype point to in the subtype object here. When I try to call the function

civic.describe;

It appear an error.

Uncaught SyntaxError: Invalid shorthand property initializer

Why 'this' keyword cannot be inherited?

Upvotes: 1

Views: 72

Answers (1)

Robby Cornelissen
Robby Cornelissen

Reputation: 97382

There are a couple of problems with your code:

  1. The way you assign the function to the object property (describe = function() { /* ... */}), is syntactically invalid.
  2. You reassign to the Honda prototype, overwriting what you had previously assigned using Object.create().

This snippet solves both issues by correctly initializing the object and using Object.assign:

let Car = function() {};
Car.prototype = {
  constructor: Car,
  numWheel: 4,
  numLight: 2,
  describe: function() {
    console.log(`This car is ${this.name} produced in ${this.version} `);
  }
}


let Honda = function(name, version) {
  this.name = name;
  this.version = version;
}
Honda.prototype = Object.assign({}, Car.prototype, {
  constructor: Honda
});

let civic = new Honda('civic', 2015);
civic.describe();

Upvotes: 2

Related Questions