给定以下 es6 类:
class Test {
constructor() {
this.foo = () => console.log('Hello World');
}
bar() {
console.log('Hello World')
}
}
foo 和 bar 有什么区别?我可以通过 this (this.foo, this.bar) 调用两者。但是,如果我在 knockoutJS 中使用此语法,Knockout 将无法找到 bar()。
class Test2 {
constructor() {
this.foo = () => this.foo(); // endless loop
}
foo() {
console.log('Hello World')
}
}
我不知道这是否有意义,但我希望您能在 Test2
中看到这些内容。主要是,我想将覆盖功能添加到我的 knockout 应用程序中。如果我从 Test1
扩展并覆盖 foo
,我将无法调用 super.foo()
。
我的目标是启用类继承,同时允许覆盖专门分配给“this”的函数(例如附加/处置)。
编辑:作为解决方法,我可以这样处理:
class Test3 {
constructor() {
this.foo = () => _foo();
}
_foo() {
console.log('Hello World')
}
}
这将允许我在 knockout 中使用 foo 并且仍然能够使用 _foo 覆盖它。
最佳答案
What is the difference between foo and bar?
参见 Use of 'prototype' vs. 'this' in JavaScript?
If I use this syntax in knockoutJS, Knockout is not able to find bar()
看起来 Knockout 没有跟上语言发展的步伐。在 class
es 上定义的方法是不可枚举的。参见 ES6 Iterate over class methods了解如何访问它们。
My goal is to enable class-inheritance while allowing to override functions that are specifically assigned to 'this' (e.g. attached/dispose).
您可以随时执行 this.foo = this.foo.bind(this);
。
关于javascript - es6 方法内部和外部构造函数 - knockout ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42683888/