【问题标题】:How to extend class onto class instance in javascript?如何在javascript中将类扩展到类实例?
【发布时间】:2017-11-08 18:37:14
【问题描述】:

我对原型非常熟悉,现在我尝试通过测试类在编译时的底层外观并将其与“原型”方法进行比较来了解类的工作原理。

当我使用原型时,我可以使用Object.setPrototypeOf 方法将一个对象“扩展”到另一个对象。我将 [Object] 类型的任何内容作为第二个参数传递并且它可以工作,但是当我将 extends 关键字与 class 一起使用时,它只需要另一个 [class] 类型的对象。

这是有效的prototype-like 方法:

function Citizen(country){
  this.country = country;
}

function Student(subject){
  this.subject = subject;
}


Object.setPrototypeOf(Student.prototype,new Citizen('Poland'));

var student = new Student('IT');
console.log(student.subject); //IT
console.log(student.country); //Poland

所以,我将 Student“扩展”到 Citizen instance 而不是 Citizen 本身(构造函数)。它工作得很好。我可以访问Citizen 实例 (student.contry) 的属性。

如何使用classextends 获得相同的结果? 我想在下面的代码中实现类似的东西,但它会抛出错误:Class extends value #<Citizen> is not a constructor or null,这似乎不如使用纯原型灵活。

class Citizen {
  constructor(subject){
    this.subject = subject;
  }
}

class Student extends new Citizen('USA') { 
  //this expects CLASS rather than instance of the class
  //Error: Class extends value #<Citizen> is not a constructor or null
  constructor(subject){
    this.subject = subject;
  }
}

var student = new Student('law');

console.log(student.subject); //law

【问题讨论】:

  • "而且效果很好。" - No, it doesn't
  • 不要为此使用Object.setPrototypeOf。不知道你从哪里得到的。
  • "class 似乎不像使用纯原型那样灵活。" - 它从来都不是故意的。类提供了一个相对严格的框架,很难搞砸。
  • @Bergi 来自 mdn。为什么?
  • @Paweł 不,extends 很好 - 它更类似于 Object.create 而不是 setPrototypeOf

标签: javascript class oop prototype extends


【解决方案1】:

如何使用类和扩展获得相同的结果?

你不能(-ish)。但更重要的是,你不应该这样做。即使使用原型方法,您仍然不应该这样做。您的原型方法应如下所示:

Object.setPrototypeOf(Student.prototype, Citizen.prototype);

同样,你的类方法应该是这样的:

class Student extends Citizen

如果出于某种原因您希望您的学生拥有一个硬编码的国家/地区,那么您可以这样做:

class Student extends Citizen {
    constructor(subject) {
        super("USA");
        this.subject = subject;
    }
}

【讨论】:

    猜你喜欢
    • 2021-10-17
    • 1970-01-01
    • 2020-04-09
    • 2010-12-14
    • 1970-01-01
    • 2017-07-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多