Skip to content Skip to sidebar Skip to footer

Javascript Inheritance With Concise Prototype Assignment Syntax

I've defined two javascript classes using this (prototype) approach: function Parent () { this.a = 1; } Parent.prototype = { hello : function () { return 'Hello I'

Solution 1:

Is merging the two prototypes the solution?

Yes.

How?

Simply write a loop that runs over the object literal and merges each property into the prototype.

function inherit(Child, Parent, methods) {
    var p = Child.prototype = Object.create(Parent.prototype);
    p.constructor = Child;
    for (var m in methods)
        p[m] = methods[m];
    return p;
}
function Child () {
    Parent.call(this);
    this.b = 2;
}
inherit(Child, Parent, {
    hello : function () {
        return "Hello I'm Child!";
    },
    setB : function (b) {
        this.b = b;
    }
});

Solution 2:

here is an example i copy from pro javascript design pattern

function extend (subClass, superClass) {
  var F = function () {};
  F.prototype = superClass.prototype;
  subClass.prototype = new F();
  subClass.prototype.constructor = subClass;

  subClass.superclass = superClass.prototype; 
  if (superClass.prototype.constructor === Object.prototype.constructor) {
    superClass.prototype.constructor = superClass;
  } // end if
} // end extend()

function Person (name) {
  this.name = name;
} // end Person()
Person.prototype.getName = function () {
  return this.name;
}; // end getName()

function Author (name, books) {
  Author.superclass.constructor.call(this, name); 
  this.books = books;
} // end Author()

extend(Author, Person);

Author.prototype.getBooks = function () {
  return this.books;
}; // end getBooks()
Author.prototype.getName = function () {
  var name = Author.superclass.getName.call(this);
  return name + " , author of " + this.getBooks();
}; // end getName()

var a = new Author("xxx", "xxx");
console.log(a.getName()); // xxx , author of xxx

the author listed three way to implement inherit: class based, prototype based and augment based.

you can read the code and maybe read the book..


Post a Comment for "Javascript Inheritance With Concise Prototype Assignment Syntax"