带有{} 的对象声明是隐藏object prototype 的简写语法:
let obj = {}; // what you wrote
let obj = new Object() // what your JS interpreter sees
obj.prototype.object // what your JS interpreter creates
这与使用class 速记语法非常相似。 But class is a double abstraction,隐藏了它实际上是在创建一个函数并且它正在使用 function prototype 这样做的事实:
// what you wrote
class test{
constructor(x){
this.x = x;
}
}
// what your JS interpreter creates
test.prototype.constructor
所以当你记录obj 并得到[object Object] 时,你的JS 解释器告诉你你已经创建了一个原型对象。您对test 感到困惑,请停下来-它们在不同的范围内,并不意味着同一件事。先学习原型。
引擎盖下的 JS
要记住的是,Javascript 是一种面向对象的语言,但不像大多数其他 OOP 那样使用基于类的继承。 Javascript 使用prototype inheritance。当您instantiate a class in JS 时,它并不是经典编程意义上的真正类。
重申一下,您的 JS class 实际上被定义为一个函数。试试看:
console.log(typeof test) //output: function
还有更多。假设我们用另一种方法进一步扩展了您的示例:
class test{
constructor(x){
this.x = x;
}
// Custom method
outputX() {
console.log(this.x)
}
}
我们实际上做了什么?如上所述,JS 解释器将读取您的类并利用function prototype 来创建它。那么这与仅仅定义一个函数有何不同呢?
因为你使用了class,所以函数原型会自动为你的新test原型分配一个构造方法。所有其他自定义方法——比如我添加的outputX——都被添加到test原型中。
// All valid
test.prototype.constructor
test.prototype.outputX
test.prototype.whateverMethodYouMake