JavaScript 深入之继承的多种方式和优缺点
本文讲解 JavaScript 各种继承方式和优缺点。但是注意:这篇文章更像是笔记,再让我感叹一句:《JavaScript 高级程序设计》写得真是太好了!
1.原型链继承
function Parent () { this.name = 'kevin'; } Parent.prototype.getName = function () { console.log(this.name); } function Child () { } Child.prototype = new Parent(); var child1 = new Child(); console.log(child1.getName()) // kevin
问题:
1.引用类型的属性被所有实例共享,举个例子:
function Parent () { this.names = ['kevin', 'daisy']; } function Child () { } Child.prototype = new Parent(); var child1 = new Child(); child1.names.push('yayu'); console.log(child1.names); // ["kevin", "daisy", "yayu"] var child2 = new Child(); console.log(child2.names); // ["kevin", "daisy", "yayu"]
2.在创建 Child 的实例时,不能向 Parent 传参
2.借用构造函数(经典继承)
function Parent () { this.names = ['kevin', 'daisy']; } function Child () { Parent.call(this); } var child1 = new Child(); child1.names.push('yayu'); console.log(child1.names); // ["kevin", "daisy", "yayu"] var child2 = new Child(); console.log(child2.names); // ["kevin", "daisy"]
优点:
- 避免了引用类型的属性被所有实例共享
- 可以在 Child 中向 Parent 传参
举个例子:
function Parent (name) { this.name = name; } function Child (name) { Parent.call(this, name); } var child1 = new Child('kevin'); console.log(child1.name); // kevin var child2 = new Child('daisy'); console.log(child2.name); // daisy
缺点:方法都在构造函数中定义,每次创建实例都会创建一遍方法。
3.组合继承
原型链继承和经典继承双剑合璧。
function Parent (name) { this.name = name; this.colors = ['red', 'blue', 'green']; } Parent.prototype.getName = function () { console.log(this.name) } function Child (name, age) { Parent.call(this, name); this.age = age; } Child.prototype = new Parent(); Child.prototype.constructor = Child; var child1 = new Child('kevin', '18'); child1.colors.push('black'); console.log(child1.name); // kevin console.log(child1.age); // 18 console.log(child1.colors); // ["red", "blue", "green", "black"] var child2 = new Child('daisy', '20'); console.log(child2.name); // daisy console.log(child2.age); // 20 console.log(child2.colors); // ["red", "blue", "green"]
优点:融合原型链继承和构造函数的优点,是 JavaScript 中最常用的继承模式。
4.原型式继承
function createObj(o) { function F(){} F.prototype = o; return new F(); }
就是 ES5 Object.create 的模拟实现,将传入的对象作为创建的对象的原型。
缺点:
包含引用类型的属性值始终都会共享相应的值,这点跟原型链继承一样。
var person = { name: 'kevin', friends: ['daisy', 'kelly'] } var person1 = createObj(person); var person2 = createObj(person); person1.name = 'person1'; console.log(person2.name); // kevin person1.friends.push('taylor'); console.log(person2.friends); // ["daisy", "kelly", "taylor"]
注意:修改 person1.name
的值,person2.name
的值并未发生改变,并不是因为 person1
和 person2
有独立的 name 值,而是因为 person1.name = 'person1'
,给 person1
添加了 name 值,并非修改了原型上的 name 值。
5. 寄生式继承
创建一个仅用于封装继承过程的函数,该函数在内部以某种形式来做增强对象,最后返回对象。
function createObj (o) { var clone = Object.create(o); clone.sayName = function () { console.log('hi'); } return clone; }
缺点:跟借用构造函数模式一样,每次创建对象都会创建一遍方法。
6. 寄生组合式继承
为了方便大家阅读,在这里重复一下组合继承的代码:
function Parent (name) { this.name = name; this.colors = ['red', 'blue', 'green']; } Parent.prototype.getName = function () { console.log(this.name) } function Child (name, age) { Parent.call(this, name); this.age = age; } Child.prototype = new Parent(); var child1 = new Child('kevin', '18'); console.log(child1)
组合继承最大的缺点是会调用两次父构造函数。
一次是设置子类型实例的原型的时候:
Child.prototype = new Parent();
一次在创建子类型实例的时候:
var child1 = new Child('kevin', '18');
回想下 new 的模拟实现,其实在这句中,我们会执行:
Parent.call(this, name);
在这里,我们又会调用了一次 Parent 构造函数。
所以,在这个例子中,如果我们打印 child1 对象,我们会发现 Child.prototype 和 child1 都有一个属性为colors
,属性值为['red', 'blue', 'green']
。
那么我们该如何精益求精,避免这一次重复调用呢?
如果我们不使用 Child.prototype = new Parent() ,而是间接的让 Child.prototype 访问到 Parent.prototype 呢?
看看如何实现:
function Parent (name) { this.name = name; this.colors = ['red', 'blue', 'green']; } Parent.prototype.getName = function () { console.log(this.name) } function Child (name, age) { Parent.call(this, name); this.age = age; } // 关键的三步 var F = function () {}; F.prototype = Parent.prototype; Child.prototype = new F(); var child1 = new Child('kevin', '18'); console.log(child1);
最后我们封装一下这个继承方法:
function object(o) { function F() {} F.prototype = o; return new F(); } function prototype(child, parent) { var prototype = object(parent.prototype); prototype.constructor = child; child.prototype = prototype; } // 当我们使用的时候: prototype(Child, Parent);
引用《JavaScript 高级程序设计》中对寄生组合式继承的夸赞就是:
这种方式的高效率体现它只调用了一次 Parent 构造函数,并且因此避免了在 Parent.prototype 上面创建不必要的、多余的属性。与此同时,原型链还能保持不变;因此,还能够正常使用 instanceof 和 isPrototypeOf。开发人员普遍认为寄生组合式继承是引用类型最理想的继承范式。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
HTML5
规范要求:脚本执行前,出现在当前
<script>
之前的<link rel="stylesheet">
必须完全载入。脚本执行会阻塞
DOM
解析。CSS
外链阻塞了脚本的执行,此时异步队列的任务该如何调度呢?我想JS
引擎主线程遇到阻塞后,这时候就会放弃当前线程的代码执行,这时候JS
引擎是空闲的,为了避免等待白白浪费时间,所以主线程才会读取任务队列,开始执行异步任务。等CSS
外链下载完成之后console.log('second script')
难道成了下一个task
?还有就是别人总结的这句话,一直不太懂,这种循坏机制到底是怎么工作的,描述的也比较抽象。
但是,我不明白的是,既然CSS会延迟脚本的执行,我把bootstrap那个换成内联样式,就是不发送http请求下载那个css样式,好像结果又变了,这时候构建CSStree好像并没有阻塞js脚本的执行,那么,到底是HTTP线程阻塞了脚本的执行,还是构建CSStree阻塞了脚本执行?
如果是HTTP线程阻塞了js的执行,这个也可以解释,为什么多个js并行下载,要等全部下载完成才执行一个道理,我继续尝试了一下,换成img标签,这个也会发送http请求,但是这个并不会阻塞脚本的执行。
如果是构建CSStree阻塞了线程,根据上面实践的结果,发现构建CSStree并没有阻塞脚本的运行。之前看到的下面的这个说法,也就不成立。
那么我的猜测就是,发送的请求是是样式文件会阻塞js脚本的执行,但为什么css会阻塞js脚本文件的执行,这个我暂时也不清楚,还有浏览器预加载一些机制也不太清楚。JS 的执行有可能依赖最新样式???难道我测的结果有问题?
@shaopower 竟然还有这么奇怪的表现,感觉开启了新的世界,看来要尽快的去探索一下~
@jawil ,其实不一定是 setTimeout(printH2) 早于 second script 的
要看 bootstrap.css 这个文件获取的时机,如果 css 已经被浏览器缓存着的话(譬如第二次访问) second script 可能会先于 setTimeout。
照理说second script 应该是会被 css 阻塞执行的。不过之前都是看的 css 在 head 里的表现,放在 body 里是不是也有阻塞一说不太清楚。
只是我测下来的现象 disable cache 的话怎么刷新 second script 肯定在最后,但是把 disable cache 勾选去掉的话,后两个出现的顺序不固定。
浏览器里面的线程也希望有个大神能分享下,之前也遇到过很奇怪的表现,譬如 js 早于 css 或者不晚于 css 10ms 以内,浏览器会等 js 执行完再渲染;如果 晚于 css 10ms 之后网络再收到 js 响应,浏览器会先渲染再执行 js。
哈哈,这道题难住我了,对这个方面并没有研究,抱歉也提供不了什么资料,不过我会把这个课题记下来,如果想明白了或者有所进展,立刻跟题主讨论哈~
博主还没写事件循环和浏览器渲染机制这块,借宝地这里有个问题提前探讨一下。
这个demo的效果是:控制台先打印出来了printH2(),setTimeout(printH2)的结果(说明此时的DOMtree已经完成),然后浏览器显示了页面,页面完全显示之后(RenderTree完成)才执行了 console.log('second script');
有个地方不明白,就是js的异步任务与UI线程之间的调度,这个demo的结果来看,DOM节点渲染之后生成DOMtree才开始执行 setTimeout(printH2)的printH2函数,所以打印出了两个h2节点。
博主能帮忙解答一下UI线程和异步任务之间的关系到底是怎么样的吗?或者对于这一块有什么好的文章学习吗