JS Inheritance: this.base = Class (); this.base () or ...?

I am trying to “get” inheritance in JS. I just found a neat way to basically copy all properties from one object to another:

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();

Note that I have a Person () class with a constructor, and its "name" attribute is generated by the constructor. The great thing is that then the employee also has a name in the constructor - and voila ', he creates the Person object using the same parameter.

If I did this using the "Prototype" method:

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..>? */
Employee.prototype.constructor = Employee;


e = new Employee('tony', 'manager')
e.introduce();

Err .... now what? I can't even do this: this.name in Employee cannot be set using the corresponding Person constructor; the creation of the Person object occurs only once in inheritance.

... ? , "" ? ?

Help!

+5
1

:

function Parent() {}

function Child() {
    Parent.call(this); // call the constructor of the parent
}

var Constr = function() {};
Constr.prototype = Parent.prototype;

Child.prototype = new Constr();
Child.prototype.constructor = Child;

, "" , Parent.prototype Child.

, Child.prototype Parent.prototype.

. , , . call [docs] apply [docs ], this, .

:

function Employee(name,title){
  this.title=title;

  Person.call(this, name);
}

.

this.base(name), , ( ), this .


, , . Google Closure library:

goog.inherits = function(childCtor, parentCtor) {
  /** @constructor */
  function tempCtor() {};
  tempCtor.prototype = parentCtor.prototype;
  childCtor.superClass_ = parentCtor.prototype;
  childCtor.prototype = new tempCtor();
  childCtor.prototype.constructor = childCtor;
}; 
+9

All Articles