JavaScript:Class.method vs Class.prototype.method

Source: Internet
Author: User
Tags function prototype


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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.