javascript 面向对象







// base class
function  Animal(name){
    // 所有的动物都有名字这个属性
    // 这只定义一个属性作为演示
    // 该属性可以被子类继承
    this.name=name||'animal';

    //  无法被子类继承
    var weight=90;

}

// 所有动物都有自己的行为
// 这只定义一个行为作为演示
Animal.prototype.behaviour= function (action) {
    console.log(this.name,':',action)
    
}


// 继承 Animal 原型 behaviour es5 语法
Cat.prototype = Object.create(Animal.prototype);

// child class
function Cat(){

    // 继承 Animal 的属性 arguments 是当前参数 数组
    // 可以理解为将 Animal 的属性 复制过来
    //  Animal 函数体中 一切使用this. 声明的属性 都将被复制
    // 如果不想被子类继承 使用 var 声明
    Animal.apply(this,arguments);
    // 或者 使用call函数来继承 使用call 传参数不方便,需要一个一个的传 apply 的好处是  传一个数组
    // Animal.call(this);

}


Dog.prototype = Object.create(Animal.prototype);
function Dog(){
    Animal.apply(this,arguments)
}

var cat = new Cat('Tom');

cat.behaviour('喵喵喵');// Tom :喵喵喵

var dog = new Dog('Bill');
    dog.behaviour('汪汪汪');//Bill : 汪汪汪


// 猫 和 狗 都 继承了 Animal 这个类


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值