【发布时间】: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) 的属性。
如何使用class 和extends 获得相同的结果?
我想在下面的代码中实现类似的东西,但它会抛出错误: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