在JavaScript ES6类上声明方法的不同方式?
我终于受够了困惑,只测试了以下三个片段:在JavaScript ES6类上声明方法的不同方式?,javascript,Javascript,我终于受够了困惑,只测试了以下三个片段: class A { constructor(height, width) { this.height = height; this.width = width; } calcArea = function() { return this.height * this.width; } } class B { constructor(height, width) { this.height = heig
class A {
constructor(height, width) {
this.height = height;
this.width = width;
}
calcArea = function() {
return this.height * this.width;
}
}
class B {
constructor(height, width) {
this.height = height;
this.width = width;
}
calcArea = () => {
return this.height * this.width;
}
}
class C {
constructor(height, width) {
this.height = height;
this.width = width;
}
calcArea() {
return this.height * this.width;
}
}
如您所见,每个类使用不同的语法来声明其calcArea
函数。我很理解普通函数和胖箭头函数在词法范围和动态范围上的区别,但在这种情况下我看不到任何区别。在这三种情况下,calcrea
的结果与预期一致。在这三种情况下,此
正确地指向类的实例
我也不清楚C类中的语法是a的快捷方式还是B的快捷方式
以这些不同的方式声明方法之间有什么区别吗?这是否回答了您的问题?前两者之间的区别:
(1,新的A(4,4)。calcArea)()
,第二个和第二个的区别:new A().hasOwnProperty(“Calcrea”)
@AsdGerte不确定我是否遵循了第一个示例….1
传递给什么?例如,通过将函数作为回调传递。看见如前所述,您还应该阅读建议的dupe target,它详细说明了A
和B
之间的区别。是的,对不起,我选择这种方式是出于习惯,但它可能会在以前没有见过的情况下造成额外的混乱。作为旁注,这里有一个例子。这只是一个很短的方法。这能回答你的问题吗?前两者之间的区别:(1,新的A(4,4)。calcArea)()
,第二个和第二个的区别:new A().hasOwnProperty(“Calcrea”)
@AsdGerte不确定我是否遵循了第一个示例….1
传递给什么?例如,通过将函数作为回调传递。看见如前所述,您还应该阅读建议的dupe target,它详细说明了A
和B
之间的区别。是的,对不起,我选择这种方式是出于习惯,但它可能会在以前没有见过的情况下造成额外的混乱。作为旁注,这里有一个例子。这只是一个很短的方法。