Note that there are some explanatory texts on larger screens.

plurals
  1. POInheritance in JS: this.base = Class(); this.base() or ...?
    text
    copied!<p>I am trying to "get" inheritance in JS. I just discovered a neat way to basically copy all properties from one object into another:</p> <pre><code>function Person(name){ this.name="Mr or Miss: "+name; this.introduce = function(){ console.log("Hi, I am "+this.name); } } function Employee(name,title){ this.title=title; this.base=Person; this.base(name); } e = new Employee('tony', 'manager') e.introduce(); </code></pre> <p>Note that I have a Person() class with a constructor, and its attribute "name" is generated by the constructor. The great thing about this is also that then employee has ALSO the name in the constructor -- and voila', it creates the Person object using the same parameter.</p> <p>If I had done this with the "Prototype" way:</p> <pre><code>function Person(name){ this.introduce = function(){ console.log("Hi, I am "+this.name); } } function Employee(name, title){ this.name = name; /* ?!?!?!?!? I can't call the proper constructor here */ this.title = title; } Employee.prototype= new Person(); /* ?!?!? NO NAME HERE..&gt;? */ Employee.prototype.constructor = Employee; e = new Employee('tony', 'manager') e.introduce(); </code></pre> <p>Err.... now what? I can't even complete this: this.name in Employee cannot be set using the proper Person constructor; the creation of a Person object happens only once in the inheritance.</p> <p>So... what am I missing? Is the first example I gave "the" way to go in my case? And is there a way to have the same result with the second example?</p> <p>Help!</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload