从 Javascript面向对象编程(三):非构造函数的继承 这里,可以看到详细的说明。
我只是将其中的例子做成html文件,便于调试罢了。
<html>
<head>
<script type="text/javascript">
function extendCopy(p) {
var c = {};
for (var i in p) {
c[i] = p[i];
}
c.uber = p;
return c;
}
function deepCopy(p, c) {
var c = c || {};
for (var i in p) {
if (typeof p[i] === 'object') {
c[i] = (p[i].constructor === Array) ? [] : {};
deepCopy(p[i], c[i]);
} else {
c[i] = p[i];
}
}
return c;
}
function object(o) {
function F() {}
F.prototype = o;
return new F();
}
var Chinese = {
nation:'中国'
};
var Doctor = object(Chinese);
Doctor.career = '医生';
alert(Doctor.nation);
Chinese.birthPlaces = ['北京','上海','香港'];
var Doctor2 = extendCopy(Chinese);
//change child
Doctor2.birthPlaces.push('厦门');
alert(Doctor2.birthPlaces);
alert(Chinese.birthPlaces);
var Doctor3 = deepCopy(Chinese);
//change child
Doctor3.birthPlaces.push('厦门2');
alert(Doctor3.birthPlaces);
alert(Chinese.birthPlaces);
</script>
</head>
<body>
Test
</body>
</html>
下面时从web developer debugger上的截图。
1.通过继承来获得Chinese的nation和birthPlaces属性。
2. 这里时浅copy,所有更改Doctor会同时更改Chinese
3. 这里时深copy,所有Doctor和Chinese互不影响。