An example method and static method analysis of JS

Source: Internet
Author: User

var person= function () {};person.say=function () {console. Log ( ' I am a person,i can say. ')}; person. prototype.getname= Functionconsole. Log ( ' My name is ' +name)}           

The above code, in fact, is very simple, the first is to define a function,js inside like the above definition of a function is actually defined a class, Next, I give you this class to add a say method, Then add a GetName method to the prototype of this class, all classes will have a prototype such attributes, this property points to the object, this is the JS prototype chain problem, I do not elaborate here. Okay, I'm going to call it this:

Person.say();Person.getName(‘Carl‘);

is not found that the first one can run normally, the second will be an error, and then take a look at the following code:

var carl=new Person;carl.say();carl.getName(‘Carl‘);

is not exactly the same as the first code, then this place actually we can see, say method is '. ' In the class above, so, it is actually a static method, then of course can be accessed directly through the class (the static method here is public), so the first sentence of the first paragraph is not the wrong, and getname this method is actually on the prototype above, Access can be made through an instance only if an instance is created.
So in summary, the definition is used directly in the class name (here is the method name) '. ' A method, then this actually creates a static method, and uses the prototype '. ' A method, actually created is an instance method, instance method is need to create an instance object for access, so, the above is what I want to say, JS inside the static method and instance method, same, static attribute and instance attribute also this reason.

An example method and static method analysis of JS

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.