When you use inheritance, you will most likely want to take an already existing functionality and then build upon it. This means creating a new object by inheriting from an existing object and then adding additional methods and properties. You can do this with one function call using a combination of the last two approaches just discussed.
You can:
function objectPlus(o, stuff) { var n; function F() {} F.prototype = o; n = new F(); n.uber = o; for (var i in stuff) { n[i] = stuff[i]; } return n; }
This function takes an object o
to inherit from and another object stuff
that has the additional methods and properties that are to be copied. Let's see this in action.
Start with the base shape
object:
var shape = { name: 'Shape', toString: function () { return this.name; } };
Create a 2D object by inheriting shape and adding more properties. The additional properties are simply created with an object literal:
var twoDee = objectPlus(shape, { name: '2D shape', toString: function () { return this.uber.toString() + ', ' + this.name; } });
Now, let's create a triangle
object that inherits from 2D and adds more properties:
var triangle = objectPlus(twoDee, { name: 'Triangle', getArea: function () { return this.side * this.height / 2; }, side: 0, height: 0 });
You can test how it all works by creating a concrete triangle my
with defined side
and height
:
var my = objectPlus(triangle, { side: 4, height: 4 }); >my.getArea(); 8 >my.toString(); "Shape, 2D shape, Triangle, Triangle"
The difference here, when executing toString()
, is that the Triangle
name is repeated twice. That's because the concrete instance was created by inheriting triangle
, so there was one more level of inheritance. You could give the new instance a name:
>objectPlus(triangle, { side: 4, height: 4, name: 'My 4x4' }).toString(); "Shape, 2D shape, Triangle, My 4x4"
This objectPlus()
is even closer to ES5's Object.create();
only the ES5 one takes the additional properties (the second argument) using something called property descriptors (discussed in Appendix C, Built-In Objects).
3.144.189.177