---
title: "Using a Mix of Prototypal Inheritance and Copying Properties"
author: "wangdun119"
date: "2012-04-12T16:06:51Z"
tags: []
categories: ["Web前端"]
slug: "using-a-mix-of-prototypal-inheritance-and-copying-properties"
draft: false
lastmod: "2012-04-12T16:08:55Z"
id: 1484573
url: "https://wangdun119.iteye.com/blog/1484573"
---

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

```java
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:

```java
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.

```java
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.

```java
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:

```java
var my = objectPlus(triangle, {side: 4, height: 4});
my.getArea()//8
my.toString()//shape,2d shape triangle,triangle
```