打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
使用Object.create()实现继承

使用Object.create()实现继承:https://www.cnblogs.com/cuew1987/p/4075027.html

 

 

一、常见继承方式

我们日常开发中常见的继承方式主要有: 1、默认模式:

1Child.prototype = new Parent();

2、借用构造函数:

123function Child(a, b, c, d) {    Parent.apply(this, arguments);}

3、借用和设置原型:

1234function Child(a, b, c, d) {    Parent.apply(this, arguments);}Child.prototype = new Parent();

4、共享原型:

1Child.prototype = Parent.prototype;

5、使用临时构造函数:

123var Proxy = function() {};Proxy.prototype = Parent.prototype;Child.prototype = new Proxy();

6、extend属性复制:

1234567891011function extend(parent, child) {    child = child || {};     for(var key in parent) {        if(parent.hasOwnProperty(key)) {            child[key] = parent[key];        }    }     return child;}

当然在一些javascript库中(jQuery),还存在浅复制和深复制。 7、原型继承模式:

1Object.create(Parent);

二、Object.create实现继承

本文将来学习第七种继承方式Object.create()方法来实现继承,关于此方法的详细描述,请戳这里。下面来通过几个实例来学习该方法的使用:

12345678910111213141516var 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());

我们再来看一个例子,再添加一个继承:

123456789101112131415161718192021222324252627282930var 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()方法实现了链式继承,及原型链的继承。如果在控制台打印出各个生成的对象,可以很清楚的看到。

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

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

来源:https://www.icode9.com/content-4-462801.html
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
深入理解JavaScript系列(45):代码复用模式(避免篇)
js 對象、原型、繼承詳解
深入理解Javascript面向对象编程
万字长文深度剖析面向对象的javascript
js如何实现继承
JavaScript语言知识收藏
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服