JavaScript方法是在类原型中定义的还是在类属性中定义的?
当我在网上研究时,我发现了不同的答案JavaScript方法是在类原型中定义的还是在类属性中定义的?,javascript,ecmascript-6,Javascript,Ecmascript 6,当我在网上研究时,我发现了不同的答案 class Foo { constructor() { this.data = []; } add(x) { // } } 上述代码是否等同于代码A或代码B 代码A: function Foo() { this.data = [], this.add = function(x) { // } } 代码B: function Foo() { t
class Foo {
constructor() {
this.data = [];
}
add(x) {
//
}
}
上述代码是否等同于代码A或代码B
代码A:
function Foo() {
this.data = [],
this.add = function(x) {
//
}
}
代码B:
function Foo() {
this.data = []
}
Foo.prototype.add = function(x) {
//
}
代码B在您的示例中,下面是从 与
function Animal() { }
Animal.prototype.speak = function(){
return this;
}
Animal.eat = function() {
return this;
}
let obj = new Animal();
let speak = obj.speak;
speak(); // global object
let eat = Animal.eat;
eat(); // global object
请注意,这是使用ES6表示法,在编写本文时不完全受支持。请参见此处了解支持ES6的内容-请参见此处了解ES6的深入文档-它们相当于B。执行
console.dir(Foo.prototype)
并亲自查看。相关:非常小但潜在重要的挑剔:ES6中的类声明本身并没有被提升,而是函数(因此,已传输回ES3-5的类别声明)被挂起。
function Animal() { }
Animal.prototype.speak = function(){
return this;
}
Animal.eat = function() {
return this;
}
let obj = new Animal();
let speak = obj.speak;
speak(); // global object
let eat = Animal.eat;
eat(); // global object