1

Given the following class in es6:

class Test {
  constructor() {
    this.foo = () => console.log('Hello World');
  }

  bar() {
    console.log('Hello World')
  }
}

What is the difference between foo and bar? I can call both via this (this.foo, this.bar). However, if I use this syntax in knockoutJS, Knockout is not able to find bar().

class Test2 {
  constructor() {
    this.foo = () => this.foo(); // endless loop
  }

  foo() {
    console.log('Hello World')
  }
}

I don't know if this makes sense, but I'd like to have what you can see in Test2. Mainly, I would like to get the override-feature into my knockout application. If I extend from Test1 and override foo, I won't be able to call super.foo().

My goal is to enable class-inheritance while allowing to override functions that are specifically assigned to 'this' (e.g. attached/dispose).

Edit: As a workaround, I can handle this like:

class Test3 {
  constructor() {
    this.foo = () => _foo();
  }

  _foo() {
    console.log('Hello World')
  }
}

This will allow me to use foo in knockout and still being able to override it using _foo.

Frame91
  • 3,670
  • 8
  • 45
  • 89

1 Answers1

2

What is the difference between foo and bar?

See Use of 'prototype' vs. 'this' in JavaScript?

If I use this syntax in knockoutJS, Knockout is not able to find bar()

Looks like Knockout is not up to date with the language development. Methods that are defined on classes are non-enumerable. See ES6 Iterate over class methods for how to access them.

My goal is to enable class-inheritance while allowing to override functions that are specifically assigned to 'this' (e.g. attached/dispose).

You can always do this.foo = this.foo.bind(this);.

Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375