JS中的类变量声明和函数声明有什么区别

问题描述 投票:0回答:1

不久前我问了这个问题:Javascript - Class Variables vs Class Methods - what is the difference?

它迅速关闭并被误解了。那好吧。现在我找到了答案。

问题是:

[下面的JS ES6中的两个声明之间有什么区别?

class C {
   doSomething = () => {}
   doSomethingElse() { }
}

javascript es6-class
1个回答
0
投票
答案是:

在类内部使用function关键字声明的函数将添加到对象的原型中,并且不会使用传播运算符{...}复制。

在类内部声明为箭头函数的函数,将使用传播运算符复制并出现在对象级别。

如果您正在使用Redux,并且状态中包含类,请使用箭头函数编写类。

class C { doSomethingFunc() { console.log("Name is name") } doSomethingVar= () => { console.log("Last name is") } } const originalInstance = new C(); const newInstance = {...originalInstance}; originalInstance.doSomethingFunc() originalInstance.doSomethingVar() newInstance.doSomethingVar() newInstance.doSomethingFunc() // ERROR: prototypal functions are not copied with spread operator.

© www.soinside.com 2019 - 2024. All rights reserved.