js继承

时间:2020-02-27 12:48:50   收藏:0   阅读:63

js继承

首先,我们应该理解,什么是继承?所谓继承,通俗讲,就是从某人处得到某些东西,大部分情况下都是儿子从父亲那继承。现在网上也有一句玩笑,叫“你想笑死我,然后继承我的蚂蚁花呗吗”。
js中的继承,同样也可以理解为上述意思,即从子从父那获取属性和方法。
在这里,我们介绍一下使用构造函数继承和prototype继承

1.构造函数继承

此方法是通过使用call或者apply将子构造函数中的this指向变为父构造函数,但是其缺点是父对象中的属性和方法并没有继承。
代码实现:

function Computer(name, type) {
    this.name = "电脑";
    this.type = "电器";
}

function Dell(name, type, color) {
    Computer.call(this,name,type);
    this.color = color;
}
  var dell1 = new Dell('blue');
  alert(dell1.name);//=>电脑

上述代码,通过call方法使得Dell继承了Computer的name和type。在输出子构造函数Dell的构造对象的name时,结果为“电脑”。

2.prototype继承

此方法主要是通过构造函数的prototype属性,将父构造函数构造的对象作为子构造函数的原型,与此同时子构造函数也继承了父构造函数,这就需要将洗构造函数指向其本身。
代码实现:

function Computer(name,type){
    this.name = "电脑";
    this.type = "电器";
}

function Dell(name, type, color) {
    Computer.call(this,name,type);
    this.color = color;
}
Dell.prototype=new Computer();
Dell.prototype.constructor=Dell;
var dell1 = new Dell('blue');
alert(dell1.name);//=>电脑
alert(dell1.type);//=>电器

————————————————————————————————————————————

原文:https://www.cnblogs.com/zuoqiaodisan/p/12371399.html

评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!