首页 > 编程知识 正文

js继承class,js继承关键字

时间:2023-12-27 22:27:40 阅读:326477 作者:RDPI

本文目录一览:

javaScript 继承的问题 class A继承class B,A中有几个对象,如何在B中添加对象呢? 求指点啊,谢谢

script type = "text/javascript"

//父类

function Person(name, age) {

//属性

this.name = name;

this.age = age;

}

//方法

Person.prototype.showName = function() {

alert(this.name);

}

Person.prototype.showAge = function() {

alert(this.age);

}

//子类

function Coder(name, age, job) {

//继承父类的属性

//调用父类的构造方法

Person.call(this, name, age);

//增加自己的属性

this.job = job;

}

//通过原型链继承父类的方法

Coder.prototype = Person.prototype;

//增加自己的方法

Coder.prototype.showJob = function() {

alert(this.job);

}

//创建一个对象测试

var programer = new Coder('pro', '25', 'programer');

programer.showName();

programer.showAge();

programer.showJob();

/script

js中实现多继承(合并多个class)

const mixinClass = (base, ...mixins) = {

    const mixinProps = (target, source) = {

      Object.getOwnPropertyNames(source).forEach(prop = {

        if (/^constructor$/.test(prop)) { return; }

        Object.defineProperty(target, prop, Object.getOwnPropertyDescriptor(source, prop));

      })

    };

    let Ctor;

    if (base  typeof base === 'function') {

      Ctor = class extends base {

        constructor(...props) {

          super(...props);

        }

      };

      mixins.forEach(source = {

        mixinProps(Ctor.prototype, source.prototype);

      });

    } else {

      Ctor = class {};

    }

    return Ctor;

  };

js 中如何定义类?如何继承类?

过去一年了啊,LZ找到答案了么

我也是初学,下面我举个简单的例子吧

htmlscript language="javascript"

function ClassA(){

this.color = "";

}

function ClassB(){

ClassA.call(this); //this是ClassB的对象

}

var b = new ClassB();

b.color="green";

document.write(b.color+"br"); //green

/script/html

定义两个类ClassA、ClassB,ClassB原本没有color这个属性,但是通过call函数将ClassA的东西都放入ClassB中,于是ClassB便继承了ClassA的属性color。

js class继承问题,希望new出子类的时候自动调用从父类继承来的方法

1.把父类的这个方法改成private 2.如果是需要一个子类可以其它子类不可以的话,那你就要考虑这样的继承是否合理了。 3.如果觉得合理并且有这钟需要的话,方法一:在父类前面不要加任何修饰符。然后子类和调用类移到 其它包里 。方法二:空方法(取巧的做法)

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。