使用Object.create()实现继承 用 Object.create实现类式继承
使用Object.create()实现继承:https://www.cnblogs.com/cuew1987/p/4075027.html
用 Object.create实现类式继承:https://www.jianshu.com/p/561432a109d6
一、常见继承方式
我们日常开发中常见的继承方式主要有: 1、默认模式:
1
|
Child.prototype = new Parent(); |
2、借用构造函数:
1
2
3
|
function Child(a, b, c, d) { Parent.apply( this , arguments); } |
3、借用和设置原型:
1
2
3
4
|
function Child(a, b, c, d) { Parent.apply( this , arguments); } Child.prototype = new Parent(); |
4、共享原型:
1
|
Child.prototype = Parent.prototype; |
5、使用临时构造函数:
1
2
3
|
var Proxy = function () {}; Proxy.prototype = Parent.prototype; Child.prototype = new Proxy(); |
6、extend属性复制:
1
2
3
4
5
6
7
8
9
10
11
|
function extend(parent, child) { child = child || {}; for ( var key in parent) { if (parent.hasOwnProperty(key)) { child[key] = parent[key]; } } return child; } |
当然在一些javascript库中(jQuery),还存在浅复制和深复制。 7、原型继承模式:
1
|
Object.create(Parent); |
二、Object.create实现继承
本文将来学习第七种继承方式Object.create()方法来实现继承,关于此方法的详细描述,请戳这里。下面来通过几个实例来学习该方法的使用:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
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()); |
我们再来看一个例子,再添加一个继承:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
|
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()方法实现了链式继承,及原型链的继承。如果在控制台打印出各个生成的对象,可以很清楚的看到。
1
2
3
4
|
//Outputs: true console.log(Child.isPrototypeOf(SubChild)); //Outputs: true console.log(Parent.isPrototypeOf(Child)); |
isPrototypeOf() 方法测试一个对象是否存在于另一个对象的原型链上。 以上就是本文对Object.create方法的描述,文中不妥之处,还望批评指正。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)