see a person in stack overflow answer, as follows
//constructor FunctionfunctionMyClass () {varprivatevariable;//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 instanceMyclass.staticmethod =function () {}; First FunctionMyClass.prototype.publicMethod=function() {//second function//The ' This ' keyword refers to the object instance //You can access only ' privileged ' and ' public ' members};varMYOBJ =NewMyClass ();//New Object InstanceMyobj.publicmethod (); Myclass.staticmethod ();
Yes, the first function has no relationship (related) with a object instance of that constructor function, you can consider it Like a ' static method '.
In JavaScript functions is first-class objects, that means you can treat them just as any object Adding a property to the function object.
The second function, as you is extending the constructor function prototype, it'll be available to all the object Insta NCEs created new
with the keyword, and the context within that function (the this
keyword) would refer to the actual obje CT instance where you call it.
Simple to understand: (Myclass.staticmethod) A constructor is also an object that can be added to a property or method on which it is added regardless of the object instance
(MyClass.prototype.publicMethod) This is an extension constructor prototype object that is used to create all object instances with the New keyword. In a function, this points to an instance object.
Reference Address:
JavaScript:Class.method vs Class.prototype.method