前一段时间,我问了一个问题:Javascript - Class Variables vs Class Methods - what is the difference?
它立即关闭并被误解。那好吧。现在我找到了答案。
问题是:
下面的JS ES6中的两个声明之间有什么区别?
class C {
doSomething = () => {}
doSomethingElse() { }
}
答案 0 :(得分: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.