JS-继承

  • 继承

继承:每个构造函数都有一个指向原型对象的指针prototype,原型中都有一个指回构造函数的指针constructor,而实例中都有一个指向原型对象的指针__proto__。当原型对象等于另外一个类型的实例就是继承。

1.原型链继承

         //将子构造函数的原型指向父类的实例

         Dog.prototype=new Animal();

         注意:console.log(dog);不打印Animal中的属性name,color等等

//定义父类类型
function Animal() {
    this.name = 'animal';
}
Animal.prototype = {
    sayName: function () {
        console.log(this.name);
    }
}

//定义子类类型
function Dog() {
    this.color = "灰色"
}
//通过将子对象的原型对象指向父对象的一个实例来完成继承
Dog.prototype = new Animal();
//子对象的方法其实是定义在了父类对象的实例上。
Dog.prototype.sayColor = function () {
    console.log(this.color);
}
var dog = new Dog();
console.log(dog);//Dog {color:"灰色"}
dog.sayColor();//灰色
dog.sayName();//animal
  1. 原型和实例的关系

        ①instanceof

        dog instanceof Dog//true

        dog instanceof Animal//true

        dog instanceof Object//true   超类Object

       ②isPrototypeOf()

       //是否是该原型派生出来的对象

       Object.prototype.isPrototypeOf(dog)//true

       Animal.prototype.isPrototypeOf(dog)//true

   2.谨慎定义

        要把给原型(Dog)添加方法放在继承后面

2.经典继承

        //继承Animal

        Animal.call(this,name,age);

function Animal(name) {
    this.name = name;
    this.colors = ["red", "gray"];
}
function Dog(name) {
    //继承了Animal
    Animal.call(this, name);
    this.color = "gray";
}
Animal.prototype.sayName = function () {
    alert(this.name);
}

var dog = new Dog();
dog.colors.push("hhh");
console.log(dog);//Dog {name:undefined,colors:["red","gray","hhh"],color:"gray"}
var animal = new Animal();
console.log(animal);//Animal {name:undefined,colors:["red","gray"]}
//如果将函数定义在构造函数中,函数复用无从谈起
//dog.sayName();在超类型的原型中定义的方法,对于子类型而言是无法看到的

       缺点:不能继承父类原型中的方法

3.组合继承

        原型链继承实现原型属性和方法的继承

        经典继承实现实例属性的继承

        Dog.prototype=new Animal();

        Animal.call(this,name,age);

function Animal(name) {
    this.name = name;
    this.colors = ["red", "gray"];
}
function Dog(name) {
    //继承了Animal(属性)-- >经典继承
    Animal.call(this, name);
    this.color = "gray";
}
Animal.prototype.sayName = function () {
    console.log(this.name);
}
//继承方法  --> 原型链继承
Dog.prototype = new Animal();
// Dog.prototype.constructor = Animal;

var dog = new Dog();
dog.colors.push("hhh");
console.log(dog);//Dog {name:undefined,colors:["red","gray","hhh"],color:"gray"}
var animal = new Animal();
console.log(animal);//Animal {name:undefined,colors:["red","gray"]}
dog.sayName();	//可以调用   undefined

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值