Extending an Object in Javascript

Wituz picture Wituz · May 3, 2012 · Viewed 289.9k times · Source

I am currently transforming from Java to Javascript, and it's a bit hard for me to figure out how to extend objects the way I want it to do.

I've seen several people on the internet use a method called extend on object. The code will look like this:

var Person = {
   name : 'Blank',
   age  : 22
}

var Robot = Person.extend({
   name : 'Robo',
   age  : 4
)}

var robot = new Robot();
alert(robot.name); //Should return 'Robo'

Does anyone know how to make this work? I've heard that you need to write

Object.prototype.extend = function(...);

But I don't know how to make this system work. If it is not possible, please show me another alternative that extends an object.

Answer

osahyoun picture osahyoun · May 3, 2012

You want to 'inherit' from Person's prototype object:

var Person = function (name) {
    this.name = name;
    this.type = 'human';
};

Person.prototype.info = function () {
    console.log("Name:", this.name, "Type:", this.type);
};

var Robot = function (name) {
    Person.apply(this, arguments);
    this.type = 'robot';
};

Robot.prototype = Person.prototype;  // Set prototype to Person's
Robot.prototype.constructor = Robot; // Set constructor back to Robot

person = new Person("Bob");
robot = new Robot("Boutros");

person.info();
// Name: Bob Type: human

robot.info();
// Name: Boutros Type: robot