Using a Mix of Prototypal Inheritance and Copying Properties

You can:
Use prototypal inheritance to clone an existing object
Copy all of the properties of another object


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;
}


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 in an anonymous 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 some
more properties.
var triangle = objectPlus(twoDee, {
name: 'Triangle',
getArea: function(){return this.side * this.height / 2;},
side: 0,
height: 0
});



Testing 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












你可能感兴趣的:(inheritance)