What is the difference between the following two declarations?
Class.method = function () { /* code */ }
Class.prototype.method = function () { /* code using this.values */ }
Is it okay to think of the first statement as a declaration of a static method, and the second statement as a declaration of an instance method?
For visual learners, when defining the function without
.prototype
With same code, if
.prototype
is added,To make it clearer,
****Note for the example above, someInstance.method() won't be executed as,
ExampleClass.method() causes error & execution cannot continue.
But for the sake of illustration & easy understanding, I've kept this sequence.****
Results generated from
chrome developer console
&JS Bin
Click on the jsbin link above to step through the code.
Toggle commented section with ctrl+/
Yes, the first one is a
static method
also calledclass method
, while the second one is aninstance method
.Consider the following examples, to understand it in more detail.
In ES5
In the above code,
isPerson
is a static method, whilesayHi
is an instance method ofPerson
.Below, is how to create an object from
Person
constructor.var aminu = new Person("Aminu", "Abubakar");
Using the static method
isPerson
.Person.isPerson(aminu); // will return true
Using the instance method
sayHi
.aminu.sayHi(); // will return "Hi Aminu"
In ES6
Look at how
static
keyword was used to declare the static methodisPerson
.To create an object of
Person
class.const aminu = new Person("Aminu", "Abubakar");
Using the static method
isPerson
.Person.isPerson(aminu); // will return true
Using the instance method
sayHi
.aminu.sayHi(); // will return "Hi Aminu"
NOTE: Both examples are essentially the same, JavaScript remains a classless language. The
class
introduced in ES6 is primarily a syntactical sugar over the existing prototype-based inheritance model.Yes, the first function has no relationship with an object instance of that constructor function, you can consider it like a 'static method'.
In JavaScript functions are first-class objects, that means you can treat them just like any object, in this case, you are only adding a property to the function object.
The second function, as you are extending the constructor function prototype, it will be available to all the object instances created with the
new
keyword, and the context within that function (thethis
keyword) will refer to the actual object instance where you call it.Consider this example:
When you create more than one instance of MyClass , you will still only have only one instance of publicMethod in memory but in case of privilegedMethod you will end up creating lots of instances and staticMethod has no relationship with an object instance.
That's why prototypes save memory.
Also, if you change the parent object's properties, is the child's corresponding property hasn't been changed, it'll be updated.