A. Static Method:
Class.method = function () { /* code */ }
method()
here is a function property added to an another function (here Class).Class.method();
new Class()
) for accessing the method(). So you could call it as a static method.B. Prototype Method (Shared across all the instances):
Class.prototype.method = function () { /* code using this.values */ }
method()
here is a function property added to an another function protype (here Class.prototype).new Class()
).Class
C. Class Method (Each instance has its own copy):
function Class () {
this.method = function () { /* do something with the private members */};
}
method()
here is a method defined inside an another function (here Class).Class.method();
new Class()
) for the method() access.new Class()
).Example:
function Class() {
var str = "Constructor method"; // private variable
this.method = function () { console.log(str); };
}
Class.prototype.method = function() { console.log("Prototype method"); };
Class.method = function() { console.log("Static method"); };
new Class().method(); // Constructor method
// Bcos Constructor method() has more priority over the Prototype method()
// Bcos of the existence of the Constructor method(), the Prototype method
// will not be looked up. But you call it by explicity, if you want.
// Using instance
new Class().constructor.prototype.method(); // Prototype method
// Using class name
Class.prototype.method(); // Prototype method
// Access the static method by class name
Class.method(); // Static method