过去 2 年我一直在使用 React
和 Redux
,但是当我在 javascript 中使用 inheritance
时,我发现了差异javascript 中这两种类型的函数声明之间。
我有一个类a
和一个类b
,它继承自类a
,每当我运行以下代码片段时,它注销
bfunc called from class a
afunc called from class b
我假设语法 bfunc = function(){
将函数放入 this
中,语法 afunc() {
将函数放入在类的原型(prototype)中,但我不太确定。有人可以解释一下这种行为吗?
class a {
afunc() {
console.log('afunc called from class a');
}
bfunc = function() {
console.log('bfunc called from class a');
}
}
class b extends a {
afunc() {
console.log('afunc called from class b');
}
bfunc() {
console.log('bfunc called from class b');
}
}
const bObject = new b();
bObject.bfunc();
bObject.afunc();
bfunc called from class a
afunc called from class b
最佳答案
你的假设是正确的。如果您执行 console.log(bObject);
,您将看到它有自己的 bfunc
属性,其中包含该函数。
由于原型(prototype)仅在对象没有自己的属性时才使用,因此即使它是由父类放入的,原型(prototype)也会优先。
关于javascript - 类内javascript中两种函数声明的区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48022420/