使用Object.create()實現繼承

zuo發表於2014-11-04

一、常見繼承方式

我們日常開發中常見的繼承方式主要有: 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方法的描述,文中不妥之處,還望批評指正。

相關文章