一、常見繼承方式
我們日常開發中常見的繼承方式主要有: 1、默認模式:
Child.prototype = new Parent();
2、借用構造函數:
function Child(a, b, c, d) {
Parent.apply(this, arguments);
}
3、借用和設置原型:
function Child(a, b, c, d) {
Parent.apply(this, arguments);
}
Child.prototype = new Parent();
4、共享原型:
Child.prototype = Parent.prototype;
5、使用臨時構造函數:
var Proxy = function() {};
Proxy.prototype = Parent.prototype;
Child.prototype = new Proxy();
6、extend屬性復制:
function extend(parent, child) {
child = child || {};
for(var key in parent) {
if(parent.hasOwnProperty(key)) {
child[key] = parent[key];
}
}
return child;
}
當然在一些javascript庫中(jQuery),還存在淺復制和深復制。 7、原型繼承模式:
Object.create(Parent);
二、Object.create實現繼承
本文將來學習第七種繼承方式Object.create()方法來實現繼承,關於此方法的詳細描述,請戳這里。下面來通過幾個實例來學習該方法的使用:
var Parent = {
getName: function() {
return this.name;
}
}
var child = Object.create(Parent, {
name: { value: "Benjamin"},
url : { value: "http://www.zuojj.com"}
});
//Outputs: Object {name: "Benjamin", url: "http://www.zuojj.com", getName: function}
console.log(child);
//Outputs: Benjamin
console.log(child.getName());
我們再來看一個例子,再添加一個繼承:
var Parent = {
getName: function() {
return this.name;
},
getSex: function() {
return this.sex;
}
}
var Child = Object.create(Parent, {
name: { value: "Benjamin"},
url : { value: "http://www.zuojj.com"}
});
var SubChild = Object.create(Child, {
name: {value: "zuojj"},
sex : {value: "male"}
})
//Outputs: http://wwww.zuojj.com
console.log(SubChild.url);
//Outputs: zuojj
console.log(SubChild.getName());
//Outputs: undefined
console.log(Child.sex);
//Outputs: Benjamin
console.log(Child.getName());
通過上面可以看出Object.create()方法實現了鏈式繼承,及原型鏈的繼承。如果在控制台打印出各個生成的對象,可以很清楚的看到。
//Outputs: true console.log(Child.isPrototypeOf(SubChild)); //Outputs: true console.log(Parent.isPrototypeOf(Child));
isPrototypeOf() 方法測試一個對象是否存在於另一個對象的原型鏈上。 以上就是本文對Object.create方法的描述,文中不妥之處,還望批評指正。
