JavaScript继承

 test2()
    {
        // 定义一个动物类
        function Animal (name) 
        {
            this.test = "Animaltest";


          // 属性
          this.name = name || 'Animal';
                      console.log("Animal______ ", this.name);
          // 实例方法
          this.sleep = function(){
            console.log(this.name + '正在睡觉!');
          }
        }
        // 原型方法
        Animal.prototype.eat = function(food) {
          console.log(this.name + '正在吃:' + food);
        };


        // 创建子类实例时,无法向父类构造函数传参   
        // function Cat()
        // {
        //     this.test33 = "1133311"
        // }
        // Cat.prototype = new Animal();
        // Cat.prototype.name = 'cat';

        // //  Test Code
        // var cat = new Cat();
        // console.log(cat.name);
        //         console.log(cat.test33);
        //  cat.eat('fish');
        // cat.sleep();
        // console.log(cat instanceof Animal); //true 
        // console.log(cat instanceof Cat); //true


// 不能继承原型属性  , 每个子类都有父类实例函数的副本,影响性能,, 实例并不是父类的实例,只是子类的实例
// 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);
// cat.sleep();
// cat.eat();
// console.log(cat.test);
// console.log(cat instanceof Animal); // false
// console.log(cat instanceof Cat); // true


// 不能继承原型属性  ,  
// function Cat(name){
//   Animal.call(this);
//   this.name = name || 'Tom';
//   console.log("cat gouzao shan");
// }
// // 不加这行继承不了原型 加了又调用了两次
// Cat.prototype = new Animal();
// Cat.prototype.constructor = Cat;
// // Test Code
// var cat = new Cat();
// console.log(cat.name);
// cat.sleep();
// cat.eat();
// console.log(cat.test);
// console.log(cat instanceof Animal); // false
// console.log(cat instanceof Cat); // true
 
    // 寄生
    function content(obj)
    {
        function F(){};
        F.prototype = obj;
        return new F();
    }
     // con的原型继承了父类的函数原型,,, 只继承了原型数据
    var con = content(Animal.prototype);

    function Cat()
    {
        // 这里调用了父类的构造函数 ,继承了父类构造函数里的属性
        Animal.call(this);
    }

    //只继承了原型数据
    Cat.prototype = con;
    // 修复cnostrcutor函数
    con.constructor = Cat;
    var cat = new Cat();
    console.log(cat.test);

    }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值