js类的继承

如何实现类的继承呢?
有如下2个构造函数:

function PeopleClass(){
    this.type = "人";    
};
PeopleClass.ptototype = {
    getType:function(){
        alert("这是一个人");
    }
};

function StudentClass(name,sex){
    this.name = name;
    this.sex = sex; 
};

如何让『学生』对象来继承『人』对象呢?可使用apply方法将父对象的构造函数绑定在子对象上,代码如下:

function PeopleClass(){
    this.type = "人";    
};
PeopleClass.ptototype = {
    getType:function(){
        alert("这是一个人");
    }
};

function StudentClass(name,sex){
    PeopleClass.apply(this,arguments);
    this.name = name;
    this.sex = sex; 
};
var stu = new StudentClass("lily","男");
alert(stu.type); //[人]

从运行的结果来看,StudentClass继承了PeopleClass的属性『人』。
方法的继承,只要循环使用父对象的prototype进行复制,即可达到继承的目的。方法如下:

function StudentClass(name,sex){
    PeopleClass.apply(this,arguments);
    var prop;
    for(prop in PeopleClass.prototype){
        var proto = this.constructor.prototype;
        if(!proto[prop]){
            proto[prop] = PeopleClass.prototype[prop];
        }
        proto[prop]["super"] = PeopleClass.prototype;
    }
    this.name = name;
    this.sex = sex; 
};

var stu = new StudentClass("lily","女");
alert(stu.type); //[人]
stu.getType(); //[这是一个人]

以上就是js中继承的实现。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
JavaScript 中,可以使用 `extends` 关键字来实现继承。如果要继承多个父的属性,可以使用 Mixin 的方式来实现。 Mixin 是一种将多个对象合并成一个对象的技术。在 JavaScript 中,可以使用 Object.assign() 方法将多个对象合并成一个新对象。我们可以将父的属性通过 Object.assign() 方法合并到子中。 下面是一个使用 Mixin 继承多个属性并添加自己内容的示例: ```js class Dog { constructor(name) { this.name = name; } bark() { console.log(`${this.name} is barking!`); } } class Cat { constructor(name) { this.name = name; } meow() { console.log(`${this.name} is meowing!`); } } class Animal { constructor(name) { this.name = name; } eat() { console.log(`${this.name} is eating!`); } } // Mixin const withJump = { jump() { console.log(`${this.name} is jumping!`); } }; class DogCat extends Animal { constructor(name) { super(name); Object.assign(this, new Dog(name), new Cat(name), withJump); } play() { console.log(`${this.name} is playing!`); } } const dogCat = new DogCat('Tom'); dogCat.bark(); // Tom is barking! dogCat.meow(); // Tom is meowing! dogCat.jump(); // Tom is jumping! dogCat.eat(); // Tom is eating! dogCat.play(); // Tom is playing! ``` 在上面的示例中,我们定义了一个 Dog 和一个 Cat ,并使用 Mixin 合并了它们的属性到 DogCat 中。同时,我们还定义了一个 Animal ,让 DogCat 继承它的属性。最后,我们定义了一个 withJump 对象,它包含了 jump() 方法,将它也合并到 DogCat 中。最终,我们创建了一个 DogCat 实例 `dogCat`,它同时具有了 Dog、Cat、Animal 和 withJump 的属性和方法。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值