你懂什么叫js继承吗
说到继承呢?肯定有很多做java的朋友都觉得是一个比较简单的东西了。毕竟面向对象的三大特征就是:封装、继承和多态嘛。但是真正对于一个javascript开发人员来说,很多时候其实你使用了继承,但其实你不知道这叫继承。今天我就借这篇文章来谈一谈继承在前端的几种实现方式。
一、 原型继承
function Animal(name = 'animal'){
this.name = name
}
Animal.prototype.eat = function(food){
console.log('dasdsa')
return `${this.name} eat ${food}`;
}
function Dog(){
}
Dog.prototype = new Animal();
var instance = new Dog();
instance.name = 'dog';
console.log(instance.eat('bone'));
console.log(instance instanceof Dog); // true
console.log(instance instanceof Animal); // true
但是原型继承有有有些缺点,来看下面一段代码:
function Animal(name = 'animal'){
this.name = name
this.skinColors = ['black','white']
}
Animal.prototype.eat = function(food){
return `${this.name} eat ${food}`;
}
function Dog(){
}
Dog.prototype = new Animal();
var instance = new Dog();
instance.name = 'keji';
instance.skinColors.push('red');
console.log(instance.eat('bone'));
console.log(instance instanceof Dog); // true
console.log(instance instanceof Animal); // true
var instance1 = new Dog()
console.log(instance1.skinColors) // [ 'black', 'white', 'red' ]
从上面的代码,我们可以清楚的发现:所有的实例都会公用一个原型链,如果一个实例中修改原型 那么所有实例的值都会被修改。
二、 构造函数继承
针对前面原型链继承可能会存在公用一个原型链的问题,那么我们可以给大家介绍一种方式:构造函数的继承。构造函数的继承相当于将父类复制给子类。
function Animal(name = 'animal'){
this.name = name
this.skinColors = ['black','white']
}
Animal.prototype.eat = function(food){
return `${this.name} eat ${food}`;
}
function Dog(){
Animal.call(this);
}
var instance = new Dog();
instance.name = 'keji';
instance.skinColors.push('red');
console.log(instance.eat('bone')); // TypeError: instance.eat is not a function
console.log(instance instanceof Dog); // true
console.log(instance instanceof Animal); // true
var instance1 = new Dog();
console.log(instance1.skinColors); // [ 'black', 'white' ]
但是这种方法也有自己缺点:
- 不能继承原型上面的属性和方法
- 复制的处理,相当于在子类中实现了所有父类的方法,影响子类的性能。
三、 组合继承
原型链继承能继承父类原型链上的属性,但是可能会存在篡改的问题;而构造函数继承不会存在篡改的问题,但是不能继承原型上面的属性。那么我们是不是可以将两者进行结合呢?
function Animal(name = 'animal'){
this.name = name
this.skinColors = ['black','white']
}
Animal.prototype.eat = function(food){
return `${this.name} eat ${food}`;
}
function Dog(){
Animal.call(this);
}
Dog.prototype = new Animal();
Dog.prototype.constructor = Dog;
var instance = new Dog();
instance.name = 'keji';
instance.skinColors.push('red');
console.log(instance.eat('bone'));
console.log(instance.skinColors) // [ 'black', 'white', 'red' ]
console.log(instance instanceof Dog); // true
console.log(instance instanceof Animal); // true
var instance1 = new Dog()
console.log(instance1.skinColors) // [ 'black', 'white' ]
这种方法呢?调用了两次父类的构造函数,有些许损耗性能,并且子类的构造函数的属性会和原型上面的属性相重合。(优先原用构造函数的属性)
四、 原型式继承
function object(obj){
function F(){}
F.prototype = obj;
return new F();
}
let Programmer = {
features:["tutou","jiaban","single"]
}
// 方式一:最原始的做法
var programmer1 = object(Programmer);
programmer1.features.push('meiqian');
console.log(programmer1.features); // [ 'tutou', 'jiaban', 'single', 'meiqian' ]
var programmer2 = object(Programmer);
console.log(programmer2.features); // [ 'tutou', 'jiaban', 'single', 'meiqian' ]
// 方式二 es中的Object.create
var programmer3 = Object.create(Programmer);
console.log(programmer3.features); // [ 'tutou', 'jiaban', 'single', 'meiqian' ]
从上面的代码很明显的可以发现:和构造函数继承一样也存在被篡改的可能,并且也不能传递参数。
五、 寄生式继承
在原型式继承的基础上面增强了对象,并返回构造函数。
function pFactory(obj){
let clone = Object.create(obj);
clone.motto = function(){
console.log('hardworking and not lazy!!')
}
return clone;
}
var programmer1 = new pFactory(Programmer);
console.log(programmer1.motto()); // hardworking and not lazy!!
console.log(programmer1.features); // [ 'tutou', 'jiaban', 'single' ]
这种继承的方法同样和原型继承一样,存在被篡改的可能。
六、 寄生组合式继承
前面说了这么多,每种继承方式都有自己的优点和缺点,那么是不是可以将这些继承的方式做一个合并:以他之长补己之短呢?来看下面一段代码:
function Animal(name = 'animal'){
this.name = name
this.skinColors = ['black','white']
}
Animal.prototype.eat = function(food){
return `${this.name} eat ${food}`;
}
function inheritPrototype(subType, superType){
var prototype = Object.create(superType.prototype);
prototype.constructor = subType;
subType.prototype = prototype;
}
function Dog(name,sound){
Animal.call(this,name);
this.sound = sound;
}
inheritPrototype(Dog,Animal);
Dog.prototype.getSound = function(){
console.log(`${this.name} ${this.sound}`);
}
var instance = new Dog('keji','wangwangwang!!!');
instance.skinColors.push('red');
console.log(instance.eat('bone'));
console.log(instance.skinColors) // [ 'black', 'white', 'red' ]
console.log(instance instanceof Dog); // true
console.log(instance instanceof Animal); // true
console.log(instance.getSound()) // keji wangwangwang!!!
var instance1 = new Dog('haha','wangwang!!!')
console.log(instance1.skinColors) // [ 'black', 'white' ]
console.log(instance1.getSound()) // haha wangwang!!!
这个例子的效率的体现在它只调用了一次父类的构造函数,这很大程度上面减少创建了不必要多余的属性。并且还能继承原型链上面的方法。这个方法是现在库的实现方法。
七、 es6的继承方法
class Animal {
constructor(name){
this.name = name;
}
get getName(){
return this.animalName()
}
animalName(){
return this.name;
}
}
class Dog extends Animal{
constructor(name,sound){
super(name);
this.sound = sound;
}
get animalFeature(){
return `${this.getName} ${this.sound}`
}
}
let dog = new Dog('keji','wangwangwang!');
console.log(dog.animalFeature); // keji wangwangwang!
其实我们晓得,class语法也是由es5语法来写的,其继承的方法和寄生组合式继承的方法一样。关于es6的类,我在代码自检的时候遇到的两个重点,值得注意下的是:
- 函数声明会提升,类声明不会。
- ES5的继承实质上是先创建子类的实例对象,然后再将父类的方法添加到this上。但是es6是先创建父类的实例对象this,然后再用子类的构造函数修改this。
你懂什么叫js继承吗的更多相关文章
- web前端开发必懂之一:JS继承和继承基础总结
首先,推荐一篇博客豪情的博客JS提高: http://www.cnblogs.com/jikey/p/3604459.html ,里面的链接全是精华, 一般人我不告诉他; 我们会先从JS的基本的设计模 ...
- 三张图搞懂JavaScript的原型对象与原型链 / js继承,各种继承的优缺点(原型链继承,组合继承,寄生组合继承)
摘自:https://www.cnblogs.com/shuiyi/p/5305435.html 对于新人来说,JavaScript的原型是一个很让人头疼的事情,一来prototype容易与__pro ...
- js继承实现
JS实现继承可以分为:对象冒充和原型链继承 其中对象冒充又包括:临时变量,call 和 apply 临时变量方法: function Person(name,sex){ this.name = nam ...
- js继承的常用方法
写在前面的话:这篇博客不适合对面向对象一无所知的人,如果你连_proto_.prototype...都不是很了解的话,建议还是先去了解一下JavaScript面向对象的基础知识,毕竟胖子不是一口吃成的 ...
- 前端面试基础回顾之深入JS继承
前言 对于灵活的js而言,继承相比于java等语言,继承实现方式可谓百花齐放.方式的多样就意味着知识点繁多,当然也是面试时绕不开的点.撇开ES6 class不谈,传统的继承方式你知道几种?每种实现原理 ...
- js继承
js继承有5种实现方式: 继承第一种方式:对象冒充 function Parent(username){ this.username = username; this.hello = function ...
- js继承之call,apply和prototype随谈
在js中,call,apply和prototype都可以实现对象的继承,下面我们看一个例子: function FatherObj1() { this.sayhello = "I am jo ...
- js继承精益求精之寄生式组合继承
一.混合/组合继承的不足 上一篇JS继承终于混合继承,认真思考一下,发现其还是有不足之处的: 空间上的冗余:在使用原型链的方法继承父类的原型属性(Animal.prototype)的同时,也在子类的原 ...
- 老生常谈--Js继承小结
一直以来,对Js的继承有所认识,但是认识不全面,没什么深刻印象.于是,经常性的浪费很多时间重新看博文学习继承,今天工作不是特别忙,有幸看到了http://www.slideshare.net/stoy ...
随机推荐
- Thinkphp模板开放给第三方编辑权限时,如何禁止模板使用php代码
首先我要吐槽一个问题:为什么在博客园发布的文章总是被其他网站采集过去,而他们采集过去后,排名比博客园还好,比如这篇文章,我把标题复制到百度搜索,结果第一页的搜索结果全部都是采集我的,而我在博客园发布的 ...
- BGP路由的手动汇总
网络拓扑 XRV1 ========================================================== !hostname XRV1!interface Loopba ...
- C#中??操作符的使用
为了实现Nullable数据类型转换成non-Nullable型数据,就有了一个这样的操作符”??(两个问号)“,双问号操作符意思是取所赋值??左边的,如果左边为null,取所赋值??右边的, 比如i ...
- 读取注册表获取Windows系统XP/7/8/10类型(使用wcscmp比较wchar[]内容)
很多方案是采用GetVersion.GetVersionEx这两个API来查询操作系统的版本号来判断当前的操作系统是Windows系列中的哪个,在Win10没有出现前,这种方法是行的通的,但是Win1 ...
- Qt VS版本添加调试器
Qt的VS版本默认是不带调试器的,可以去百度一个WinDbg,如下图所示. 将其中的cdb.exe添加到Qt Creator构建和运行的Debuggers标签页即可,如下图所示. http://blo ...
- python中的函数名,闭包,迭代器
一.函数名 函数名是一个变量,但它是一个特殊的变量,与括号配合可以执行函数的变量,单纯print()出的是一个内存地址. def func(): print('你说你有点难追') print(func ...
- 深度强化学习day01初探强化学习
深度强化学习 基本概念 强化学习 强化学习(Reinforcement Learning)是机器学习的一个重要的分支,主要用来解决连续决策的问题.强化学习可以在复杂的.不确定的环境中学习如何实现我们设 ...
- CodeSmith使用SQLite Provider找不到请求的 .Net Framework 数据提供程序
关于CodeSmith5使用SQLite Provider时的报错:System.BadImageFormatException: 未能加载文件或程序集“System.Data.SQLite,.... ...
- sublimetext插件安装
sublimetext 一.下载地址: https://www.sublimetext.com/ 二.安装Package Control 方式一: Ctrl + Shift + P , 输入insta ...
- c++汉诺塔相关知识总结1
困扰已久,难以攻克的汉诺塔总结来啦 Part One 汉诺塔到底是什么呢? 汉诺塔(Tower of Hanoi)源于印度传说中,大梵天创造世界时造了三根金钢石柱子,其中一根柱子自底向上叠着64片黄金 ...