码迷,mamicode.com
首页 > Web开发 > 详细

js继承

时间:2020-02-27 12:56:22      阅读:74      评论:0      收藏:0      [点我收藏+]

标签:this   com   fun   script   介绍   没有   理解   结果   class   

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);//=>电器

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

js继承

标签:this   com   fun   script   介绍   没有   理解   结果   class   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!