使用Object.create()实现继承

王朝学院·作者佚名  2016-05-22
窄屏简体版  字體: 小  |  中  |  大  |  超大  

使用Object.create()实现继承一、常见继承方式我们日常开发中常见的继承方式主要有: 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: Benjaminconsole.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.comconsole.log(SubChild.url);//Outputs: zuojjconsole.log(SubChild.getName());//Outputs: undefinedconsole.log(Child.sex);//Outputs: Benjaminconsole.log(Child.getName());

通过上面可以看出Object.create()方法实现了链式继承,及原型链的继承。如果在控制台打印出各个生成的对象,可以很清楚的看到。

//Outputs: trueconsole.log(Child.isPrototypeOf(SubChild));//Outputs: trueconsole.log(Parent.isPrototypeOf(Child));

isPrototypeOf() 方法测试一个对象是否存在于另一个对象的原型链上。 以上就是本文对Object.create方法的描述,文中不妥之处,还望批评指正。

 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
© 2005- 王朝網路 版權所有 導航