'this' keyword in Javascript inheritence chain

612 views javascript
-2

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?

answered question

describe = function??? What is this suppose to do? Apart from that typo, numWheel and numLight should be a part of constructor and not prototype. Properties on prototype are shared across objects

what do you mean?

I mean, it should be describe: function

Oh. But when i changed it back to describe: function as you said, it appear undefined

1 Answer

3

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({
  constructor: Honda
}, Car.prototype);

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

posted this

Have an answer?

JD

Please login first before posting an answer.

Ads

Categories