一、构造函数的继承:
1、构造函数绑定:使用call或者apply,将父对象的构造函数绑定在子对象上:
function Animal () {
this.type = "";
}
funtion Dog (name, color) {
Animal.apply(this, arguments);
this.name = name;
this.color = color;
}
2、prototype模式:
function Animal () {
this.type = "";
}
funtion Dog (name, color) {
this.name = name;
this.color = color;
}
Dog.prototype = new Animal();
Dog.prototype.constructor = Dog;
3、直接继承prototype:此种方法效率高,更节省内存,但有一个缺点:Dog.prototype和Animal.ptototype指向同一个对象,所以对Dog.prototype的任何修改都会反应到Animal.ptototype。
function Animal () {
this.type = "";
}
funtion Dog (name, color) {
this.name = name;
this.color = color;
}
Dog.prototype = Animal.prototype;
4、利用空对象作为中介:
function Animal () {
this.type = "";
}
funtion Dog (name, color) {
this.name = name;
this.color = color;
}
var F = function () {};
F.prototype = Animal.prototype;
Dog.prototype = new F();
Dog.prototype.constructor = Dog;
5、拷贝继承:
function Animal () {
this.type = "";
}
funtion Dog (name, color) {
this.name = name;
this.color = color;
}
function extend (child, parent) {
var p = parent.prototype,
c = child.prototype;
for (var i in p) {
c[i] = p[i];
}
c.uber = p;
}
extend(Dog, Animal);
extend()函数的作用是将父对象的prototype的属性一一拷贝给child对象的prototype。
二、非构造函数的继承:
1.object()方法:
var Animal = {
type: ""
}
function object (o) {
function F () {};
F.prototype = o;
return new F();
}
var Dog = object(Animal);
Dog.name = "someOne";
2.浅拷贝:
var Animal = {
type: "animal"
}
function extend(p) {
var c = {};
for (var i in p) {
c[i] = p[i];
}
c.uber = p;
return c;
}
var Dog = extend(Animal);
Dog.name = "someOne";
alert(Dog.type);
但是当父对象的属性为一个数组或对象时,那么子对象获得的只是一个内存地址,而不是真正的拷贝,因此存在父对象被改动的可能。
var Animal = {
type: "animal",
name: ["test1", "test2", "test3"]
}
function extend(p) {
var c = {};
for (var i in p) {
c[i] = p[i];
}
c.uber = p;
return c;
}
var Dog = extend(Animal);
Dog.name.push("test4");
alert(Dog.name);
alert(Animal.name);
var Animal = {
type: "animal",
name: ["test1", "test2", "test3"]
}
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];
}
}
c.uber = p;
return c;
}
var Dog = deepCopy(Animal);
Dog.name.push("test4");
alert(Dog.name);
alert(Animal.name);