我们都知道,Javascript中是没有"类"这个概念的。但是在诸多环境中,有时又需要我们手动去实现类似java中的类和继承。下面我们来探索一下,如何才能完美实现js中的类和继承。
创建类
我们可以很简单的通过构造函数来实现一个类
// 创建类
function Animal(name, sex) {
this.name = name;
this.sex = sex;
}
Animal.prototype.say = function() {
console.log('i m animal');
}
可以直接new出实现这个类的对象。
// 创建对象
var cat = new Animal('cat', 'man');
console.log(cat.name)
console.log(cat.sex)
console.log(cat.say())
实现继承
下面我们来谈谈js中类的继承。
- 原型链继承
第一种方式就是我们经常听到的原型链继承。
function Cat(name, sex) {
Animal.call(this, name, sex);
}
Cat.prototype = new Animal;
var maoxian = new Cat('maoxian', 'nv');
maoxian.say();
console.log(cat.name)
console.log(cat.sex)
console.log(cat.say())
介绍:在这里我们可以看到new了一个空对象,这个空对象指向Animal并且Cat.prototype指向了这个空对象,这种就是基于原型链的继承。
特点:基于原型链,既是父类的实例,也是子类的实例
缺点:无法实现多态继承
- 构造继承
function Cat(name) {
Animal.call(this)
}
var maoxian = new Cat('maoxian');
console.log(maoxian.name);
console.log(maoxian.sex);
maoxian.say()
特点:可以实现多继承
缺点:只能继承父类实例的属性和方法,不能继承原型上的属性和方法。
- 组合继承
function Cat(name){
Animal.call(this);
this.name = name || 'Tom';
}
Cat.prototype = new Animal();
Cat.prototype.constructor = Cat;
// Test Code
var cat = new Cat();
console.log(cat.name);
console.log(cat.sleep());
console.log(cat instanceof Animal); // true
console.log(cat instanceof Cat); // true
特点:可以继承实例属性/方法,也可以继承原型属性/方法
缺点:调用了两次父类构造函数,生成了两份实例
- 寄生组合式继承
上面的组合继承
借用构造函数实现了继承独享属性和方法
借用原型链继承实现了继承原型链上的属性和方法
但是仔细会发现调用了两次类构造函数。
寄生继承就是不用实例化父类了,直接实例化一个临时副本实现了相同的原型链继承。(即子类的原型指向父类副本的实例从而实现原型共享)
其实感觉意义不大。。。😓
function Cat(name){
Animal.call(this);
this.name = name || 'Tom';
}
(function(){
// 创建一个没有实例方法的类
var Super = function(){};
Super.prototype = Animal.prototype;
//将实例作为子类的原型
Cat.prototype = new Super();
})();
// Test Code
var cat = new Cat();
console.log(cat.name);
console.log(cat.sleep());
console.log(cat instanceof Animal); // true
console.log(cat instanceof Cat); //true
其实类和继承在实战中用的很少,js毕竟不是基于类的语言,只是面试中有时会问到。有帮助的话给点个赞呗~~
网友评论