本文共 2598 字,大约阅读时间需要 8 分钟。
封装、继承以及多态是面向对象的共有特性,js作为面向对象的语言同样也支持这三个特性。
**封装:**当你需要隐藏一些属性和方法的时候,可以将这些属性和方法进行封装,然后通过外部接口(也就是公共的方法)进行调用。 举个例子:Title
运行结果:
原型链继承: 将父类的实例作为子类的原型,使用prototype关键字进行继承
举个例子://原型继承 Cat.prototype = new Animal(); Cat.prototype.name = 'cat'; var cat = new Cat(); document.writeln(cat.name+""); cat.eat('fish'); cat.sleep(); document.writeln( (cat instanceof Animal) ); //true
运行结果:
function Cat(name){ var instance = new Animal(); instance.name = name || 'Tom'; return instance; } var cat = new Cat(); document.writeln(cat.name+""); cat.sleep(); document.writeln("Is Animal:"); document.writeln(cat instanceof Animal); // true document.writeln(""); document.writeln("Is Cat:"); document.writeln(cat instanceof Cat); // false document.writeln("");
运行结果:
//组合继承function Cat(name){ Animal.call(this); this.name = name || 'Tom';}Cat.prototype = new Animal();Cat.prototype.constructor = Cat;var cat = new Cat();document.writeln(cat.name+"");cat.sleep();document.writeln("Is Animal:");document.writeln(cat instanceof Animal); // truedocument.writeln("");document.writeln("Is Cat:");document.writeln(cat instanceof Cat); // falsedocument.writeln("");
运行结果:
//寄生组合继承 function Cat(name){ Animal.call(this); this.name = name || 'Tom'; } ( function(){ // 创建一个没有实例方法的类 var Super = function(){}; Super.prototype = Animal.prototype; //将实例作为子类的原型 Cat.prototype = new Super(); Cat.prototype.constructor = Cat; } )(); var cat = new Cat(); document.writeln(cat.name+""); cat.sleep(); document.writeln("Is Animal:"); document.writeln(cat instanceof Animal); // true document.writeln(""); document.writeln("Is Cat:"); document.writeln(cat instanceof Cat); // false document.writeln("");
运行结果:
优点:解决了以上其他继承的缺点
缺点:子类的实现过程过于复杂 **多态:**就是在执行同一操作且作用于不同对象时,返回不同的结果 。 这个就是把Cat之类的换成Dog之类的类后执行不同的操作转载地址:http://fqzj.baihongyu.com/