javascript的继承——构造函数继承

构造函数继承方式:

Father.call(this, args);

构造函数继承的几个特点:

  1. 父类构造函数中的属性和方法都可以被子类继承;
  2. 父类原型上的属性和方法无法被继承;
  3. 父类实例上的属性和方法无法被继承;
  4. 父类构造函数中的属性和方法在所有子类实例中是不共享的;
  5. 创建子类实例时可以向父类构造函数传参;
  6. 允许多重继承(同时继承多个不同的父类)。

下面上一个构造函数继承的例子:

var Father = function (id) {
    //父类构造函数中的属性和方法可以被继承
    this.id = id;
    this.type = "father";
    this.getId = function () {
        return this.id;
    };
    this.getType = function () {
        return this.type;
    };
};
var Mother = function (id) {
    this.mType = "mother";
};
//父类原型上的属性和方法无法被继承
Father.prototype.gender = "male";
Father.prototype.getGender = function () {
    return this.gender;
};

//父类实例上的属性和方法无法被继承
var father = new Father();
father.job = "driver";
father.getJob = function () {
    return this.job;
};

var Son = function (id) {
    //允许多重继承
    Father.call(this, id);
    Mother.call(this);
};
var son1 = new Son(1);
//打印结果为father father,表示:子类可以正常调用父类构造函数中的属性和方法
console.log(son1.type + " " + son1.getType());
//下面的打印会出错,提示son1.getGender不是方法,表示:子类无法调用父类原型上的属性和方法
// console.log(son1.getGender());
//打印结果为undefined driver driver,表示:子类无法获取父类实例上的属性(同样也无法调用父类实例上的方法)
console.log(son1.job + " " + father.job + " " + father.getJob());
//打印结果为father mother,表示:子类可以同时继承多个父类
console.log(son1.type + " " + son1.mType);
var son2 = new Son(2);
//打印结果为1 2,表示:父类构造函数中的属性和方法在所有子类实例中是不共享的
console.log(son1.id + " " + son2.id);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值