JavaScript syntax: Difference between revisions

Content deleted Content added
Nelsonkam (talk | contribs)
Inheritance: Improved formatting for better rendering on mobile version.
Tags: Mobile edit Mobile web edit
Nelsonkam (talk | contribs)
Methods: Improved formatting for better rendering.
Tags: Mobile edit Mobile web edit
Line 1,242:
A [[method (computer science)|method]] is simply a function that has been assigned to a property name of an object. Unlike many object-oriented languages, there is no distinction between a function definition and a method definition in object-related JavaScript. Rather, the distinction occurs during function calling; a function can be called as a method.
 
When called as a method, the standard local variable ''<tt>{{mono|this</tt>}}'' is just automatically set to the object instance to the left of the "<tt>{{mono|.</tt>}}". (There are also ''<tt>{{mono|call</tt>}}'' and ''<tt>{{mono|apply</tt>}}'' methods that can set ''<tt>{{mono|this</tt>}}'' explicitly—some packages such as [[jQuery]] do unusual things with ''<tt>{{mono|this</tt>}}''.)
 
In the example below, Foo is being used as a constructor. There is nothing special about a constructor - it is just a plain function that initialises an object. When used with the ''<tt>{{mono|new</tt>}}'' keyword, as is the norm, ''<tt>{{mono|this</tt>}}'' is set to a newly created blank object.
 
Note that in the example below, Foo is simply assigning values to slots, some of which are functions. Thus it can assign different functions to different instances. There is no prototyping in this example.