ITeye博客

Using a Mix of Prototypal Inheritance and Copying Properties

wangdun119 · 2012-04-12 16:06 · JavaScript · Web前端 · Markdown

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

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。