Skip to content
Advertisement

In javascript, what’s the difference between an instance function and instance variable of type Function?

I know one of the difference is that instance variables of type Function automatically bind to the class. For example:

JavaScript
JavaScript

Why is this and are there other difference between these two ways of writing an instance function?

Advertisement

Answer

You can check what these ways are acting on the Dog.prototype object:

Method definition:

JavaScript

Public class field [MDN]:

JavaScript

In the first case you define a function in the class prototype, while in the latter you define the variable in the instance at “constructor time”, as for any other variable.

The latter is the same as doing:

JavaScript

Remember that the Public class fields are still not introduced in the ECMAs standards, so many JS environments could not support them, you should use some tools like Babel in order to achieve back compatibility. Some behaviours are still application dependant for this reason (like definition precedence).

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement