0

I'm a newbie with Node/Javascript (ES6). See example here below:

class MyClass {

    myTest() {
          console.log('it works')
        }

    runMyTest() {
          this.myTest()
        }

}

if I omit the this. in the this.myTest() line I get the runtime error:

      myTest()
      ^

ReferenceError: myTest is not defined

It seems to me to be mandatory to invoke methods declared in the same object (a Class Object in this case) of the caller, need the this.method()

That's correct?

In a similar way, I see that a parent method (of a subclassed object) requires super.parentMethod().

Coming from Ruby/other OO languages that sound weird to me.

Why the reason for mandatory this. / super. in JS?


UPDATE:

small workaround I found (to avoid this.method repetition):

class MyClass {

    myTest() {
          console.log('it works')
        }

    runMyTestManyTimes() {
          const mytest = this.mytest

          myTest()
          ...
          myTest()
          ...
          myTest()
          ...

        }

}
3
  • Try this example Commented Sep 10, 2018 at 16:02
  • The most direct answer would be because that's simply what the language specification requires. this is the calling context, whereas omission of this will only lookup the identifier from the scope, and call the function without a calling context if it's in scope, which in this case it's not. Commented Sep 10, 2018 at 16:11
  • I don't know Ruby (aside from basics for editing e.g. Vagrantfiles), but Java and Python both work this way. I thought Ruby used @ for this. Does it really let you call methods with no referent? Commented Sep 10, 2018 at 16:23

2 Answers 2

3

Because this refers to that instance ofMyClass ( with the class methods on the prototype ) and without it, your method doesn't see the function because it's not looking in the correct place. It would use whatever is in it's scope i.e if the function myTest() was declared outside of the class globally.

enter image description here

Sign up to request clarification or add additional context in comments.

1 Comment

Yeah, I was about to update it. It refers to that instance and has the prototypes of the class methods Edit: updated, anyone correct me if I'm wrong, thanks
1

That's because unlike Java or C# (which is most likely where you've seen this practice from), JavaScript can have functions that are not part of the class.

What will you do in this case?

class MyClass {
  myTest() {
    console.log('it works');
  }

  runMyTest() {
    myTest(); // oops
  }
}

function myTest() {
  console.error('It does not work! Oh my god everything is on fire!');
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.