function Father(name) { this.name = name; } Father.prototype.getName = function () { return this.name; }; function Son(name,age) { Father.call(this,name); this.age = age; } Son.prototype = new Father(); Son.prototype.getAge = function () { return this.age; }; var father = new Father("Tom"); var son = new Son("Jack",18); console.log(father.getName());//Tom console.log(son.getName());//Jack//继承父类Father的getName()方法 console.log(son.getAge());//18
多态机制实现
function Person(name) { this.name = name; if (typeof this.getName !== "function"){ Person.prototype.getName = function () { return this.name; } } if (typeof this.toEat !== "function"){ Person.prototype.toEat = function (animal) { console.log( this.getName() + "说去吃饭:"); animal.eat(); } } } function Animal(name) { this.name = name; if (typeof this.getName !== "function"){ Animal.prototype.getName = function () { return this.name; } } } function Cat(name) { Animal.call(this,name); if (typeof this.eat !== "function"){ Cat.prototype.eat = function () { console.log(this.getName() + "吃鱼"); } } } Cat.prototype = new Animal(); function Dog(name) { Animal.call(this,name); if (typeof this.eat !== "function"){ Dog.prototype.eat = function () { console.log(this.getName() + "啃骨头"); } } } Dog.prototype = new Animal(); var person = new Person("Tom"); person.toEat(new Cat("cat"));//Tom说去吃饭:cat吃鱼 person.toEat(new Dog("dog"));//Tom说去吃饭:dog啃骨头
以上这篇老生常谈javascript的面向对象思想就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持脚本之家。
您可能感兴趣的文章: