ref – https://stackoverflow.com/questions/1635116/javascript-class-method-vs-class-prototype-method
1 |
Class.method = function () { /* code */ } |
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.
1 |
Class.prototype.method = function () { /* code using this.values */ } |
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 (the this keyword) will refer to the actual object instance where you call it.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
// constructor function function MyClass () { var privateVariable; // private member only available within the constructor fn this.privilegedMethod = function () { // it can access private members //.. }; } // A 'static method', it's just like a normal function // it has no relation with any 'MyClass' object instance MyClass.staticMethod = function () {}; MyClass.prototype.publicMethod = function () { // the 'this' keyword refers to the object instance // you can access only 'privileged' and 'public' members }; var myObj = new MyClass(); // new object instance myObj.publicMethod(); MyClass.staticMethod(); |
When MyClass.prototype.publicMethod can access ‘privileged’ members, it means you can access privileged properties and functions from constructor function.
When MyClass.prototype.publicMethod can access ‘public’ members, it means you can access public functions from the prototype, like so:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
function Queue() { // privileged this._head = null; this.privileged = function() { } } // public Queue.prototype.print = function() { this.head; // access privileged this.haha(); // access public } // public Queue.prototype.haha = function() { console.log('ha! ha!'); } |