浅谈JavaScript的面向对象思想(5)


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啃骨头

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/882e7416256eb145d8b5e8a58ec6a80d.html