在JavaScript中模拟类(class)及类的继承关系
Javascipt语法不支持"类"(class)[es6已经支持],但是有模拟类的方法。今天我主要谈谈Javascipt中模拟“类”的方法及js中继承的总结和回顾。
js中实现“类”与继承,既是重点,又是难点。很多同学可能都对js中“类”与继承都有所了解,但是深入剖析的时候,感觉力不从心、模棱两可。
我们先来总结一下js定义“类”的几种方法:
方法一:构造函数法
这个方法是比较经典的方法,我们会经常见到。生成实例的时候,使用new关键字。类的属性和方法,还可以定义在构造函数的prototype对象之上。
functionPerson(name,age,job){ this.name=name; this.age=age; this.job=job; } Person.prototype.sayName=function(){ alert(this.name); } varperson1=newPerson("张三","29","webfrontpagemanager"); varperson2=newPerson("李四","22","doctor"); person1.sayName();//弹出"张三" console.log(person2.name)//输出“李四”
方法二:Object.create()法
方法Object.creat()作为new操作符的替代方案是ES5之后才出来的。用这个方法,"类"就是一个对象,不是函数。
varmyMammal={ name:'HerbtheMammal', get_name:function(){ returnthis.name; }, says:function(){ returnthis.saying||''; } } varmyCat=Object.create(myMammal); myCat.name='Henrietta'; myCat.saying='meow'; myCat.get_name=function(){ console.log(this.says+''+this.name+this.says); } myCat.get_name();
输出:
function(){ returnthis.saying||''; }Henriettafunction(){ returnthis.saying||''; }
目前,各大浏览器的最新版本(包括IE9)都部署了这个方法。如果遇到老式浏览器,可以用下面的代码自行部署。
if(!Object.create){ Object.create=function(o){ functionF(){} F.prototype=o; returnnewF(); }; }
方法三:极简主义法
封装
这种方法不使用this和prototype,代码部署起来非常简单。首先,它也是用一个对象模拟"类"。在这个类里面,定义一个构造函数creatFn(),用来生成实例。
varDog={ creatFn:function(){ //somecodehere } };
然后,在creatFn()里面,定义一个实例对象,把这个实例对象作为返回值。
varDog={ creatFn:function(){ vardog={}; dog.name="狗狗"; dog.makeSound=function(){alert("汪汪汪");}; returndog; } };
使用的时候,调用creatFn()方法,就可以得到实例对象。
vardog1=Dog.creatFn(); dog1.makeSound();//汪汪汪
这种方法的好处是,容易理解,结构清晰优雅,符合传统的"面向对象编程"的构造,因此可以方便地部署下面的特性。
继承
让一个类继承另一个类,实现起来很方便。只要在前者的creatFn()方法中,调用后者的creatFn()方法即可。先定义一个Animal类。
varAnimal={ creatFn:function(){ varanimal={}; animal.eat=function(){alert("吃饭饭");}; returnanimal; } };
然后,在Dog的creatFn()方法中,调用Animal的creatFn()方法。
varDog={ creatFn:function(){ vardog=Animal.creatFn(); dog.name="狗狗"; dog.makeSound=function(){alert("汪汪汪");}; returndog; } };
这样得到的Dog实例,就会同时继承Dog类和Animal类。
vardog1=Dog.creatFn(); dog1.eat();//吃饭饭
私有属性和私有方法
在creatFn()方法中,只要不是定义在dog对象上的方法和属性,都是私有的。
varDog={ creatFn:function(){ vardog={}; varsound="汪汪汪"; dog.makeSound=function(){alert(sound);}; returndog; } };
上例的内部变量sound,外部无法读取,只有通过dog的公有方法makeSound()来读取。
vardog1=Dog.creatFn(); alert(dog1.sound);//undefined
数据共享
有时候,我们需要所有实例对象,能够读写同一项内部数据。这个时候,只要把这个内部数据,封装在类对象的里面、creatFn()方法的外面即可。
varDog={ sound:"汪汪汪", creatFn:function(){ vardog={}; dog.makeSound=function(){alert(Dog.sound);}; dog.changeSound=function(x){Dog.sound=x;}; returndog; } };
然后,生成两个实例对象:
vardog1=Dog.creatFn(); vardog2=Dog.creatFn(); dog1.makeSound();//汪汪汪
这时,如果有一个实例对象,修改了共享的数据,另一个实例对象也会受到影响。
dog2.changeSound("呜呜呜"); dog1.makeSound();//呜呜呜
js继承
关于继承,网上也有很多资料可以查询,但是很多朋友对其理解的不够深入。讲到继承,假如你不去查资料,猛地一下,可能说不出个所以然来。这就说明我们的基础知识打的不够扎实。没有理解透彻。今天,我站在前辈的基础之上,再来和大家一起回顾一下这个继承。
继承最常用的两种方式如下:
- 原型链继承(对象间的继承)
- 类式继承(构造函数间的继承)
原型链继承
什么是原型链继承?这里我就不说什么定义了。其实就是用prototype继承父级。
举个例子:
functionParent(){ this.name='mike'; } functionChild(){ this.age=12; } Child.prototype=newParent();//Child继承Parent,通过原型,形成链条 vartest=newChild(); alert(test.age); alert(test.name);//得到被继承的属性 //继续原型链继承 functionBrother(){//brother构造 this.weight=60; } Brother.prototype=newChild();//继续原型链继承 varbrother=newBrother(); alert(brother.name);//继承了Parent和Child,弹出mike alert(brother.age);//弹出12
上面例子,通过原型,形成链条,Child继承了Parent,Brother有继承了Child,最后brother既有Child和Parent的属性,又有自己的属性。这就是原形链的继承。
类式继承(借用构造函数)
类式继承一般是通过运用call或者apply进行子类型构造函数的内部调用超类型的构造函数。举个例子:
functionParent(age){ this.name=['mike','jack','smith']; this.age=age; } functionChild(age){ Parent.call(this,age); } vartest=newChild(21); alert(test.age);//21 alert(test.name);//mike,jack,smith test.name.push('bill'); alert(test.name);//mike,jack,smith,bill
上面的两种继承是最基本的两种继承方式。
此外还有一些继承方式,我们一起来看一下!
组合继承
组合继承通常是上面两种继承方式组合在一起使用的继承方式。
举例如下:
functionParent(age){ this.name=['mike','jack','smith']; this.age=age; } Parent.prototype.run=function(){ returnthis.name+'areboth'+this.age; }; functionChild(age){ Parent.call(this,age);//对象冒充,给超类型传参 } Child.prototype=newParent();//原型链继承 vartest=newChild(21);//写newParent(21)也行 alert(test.run());//mike,jack,smithareboth21
原型式继承
和上面讲的原形链式继承只有一字之差,但是不是同一个内容。我们所说的原型式继承,就是我们上节课所讲的,通过Object.create()方式来创建新的类。因为这种方式老式浏览器不支持。因此,假如我们不用Object.create(),也可以有替代法,方式如下:
functionobj(o){ functionF(){} F.prototype=o; returnnewF(); }
这个函数,就实现了我们Object.create()创建类的方式!
因此举例如下:
functionobj(o){ functionF(){} F.prototype=o; returnnewF(); } varbox={ name:'trigkit4', arr:['brother','sister','baba'] }; varb1=obj(box); alert(b1.name);//trigkit4 b1.name='mike'; alert(b1.name);//mike alert(b1.arr);//brother,sister,baba b1.arr.push('parents'); alert(b1.arr);//brother,sister,baba,parents varb2=obj(box); alert(b2.name);//trigkit4 alert(b2.arr);//brother,sister,baba,parents
寄生式继承
举例如下:
functioncreatAnother(original){ varclone=newObject(original); clone.sayHi=function(){ alert("hi") }; returnclone; } varperson={ name:"haorooms", friends:["hao123","zhansan","lisi"] } varantherPerson=creatAnother(person); antherPerson.sayHi();//hi
寄生组合式
functioninheritPrototype(subType,superType){ varprototype=Object.creat(superType.prototype); prototype.constructor=subType; subType.prototype=prototype; }; functionSuperType(name){ this.name=name; this.colors=['red','blue','green']; } SuperType.prototype.sayName=function(){ console.log(this.name); } functionSubType(name,age){ //继承属性 SuperType.call(this,name); this.age=age; } //继承方法 inheritPrototype(SubType,SuperType); SubType.prototype.sayAge=function(){ console.log(this.age); } varinstance=newSubType();
类的继承,基本上就是如上几种方式。下面再简单的说一下ES6的class类吧!
es6实现类
//定义类 classPoint{ constructor(x,y){ this.x=x; this.y=y; } toString(){ return'('+this.x+','+this.y+')'; } } varpoint=newPoint(2,3); point.toString()//(2,3) point.hasOwnProperty('x')//true point.hasOwnProperty('y')//true point.hasOwnProperty('toString')//false point.__proto__.hasOwnProperty('toString')//true
Class的继承
classColorPointextendsPoint{ constructor(x,y,color){ super(x,y);//调用父类的constructor(x,y) this.color=color; } toString(){ returnthis.color+''+super.toString();//调用父类的toString() } }