Five methods for calling functions in JavaScript

Source: Internet
Author: User

This article details the methods and principles of various function calls in Javascript, which is helpful for understanding JavaScript Functions!

JavaScript: five methods to call Functions

Again and again, I found that Javascript code with bugs is caused by failing to really understand how Javascript Functions work (by the way, I wrote a lot of such code ). javaScript has the feature of functional programming. When we choose to face it, this will become the obstacle for us to move forward.
As a beginner, We will test five function call methods. On the surface, we will think that those functions are very similar to those in C, however, we can see that there are still very important differences. Ignoring these differences will undoubtedly lead to bugs that are difficult to track. First, let's create a simple function. this function will be used later. this function only returns the current value of this and the two provided parameters.

<script type="text/javascript">function makeArray(arg1, arg2){    return [ this, arg1, arg2 ];}</script>


The most common method, but unfortunately, global function calls
When learning Javascript, we learned how to use the syntax in the above example to define functions.
, We also know that calling this function is very simple. What we need to do is:

makeArray('one', 'two');// => [ window, 'one', 'two' ]Wait a minute. What's that windowalert( typeof window.methodThatDoesntExist );// => undefinedalert( typeof window.makeArray);// =>window.makeArray('one', 'two');// => [ window, 'one', 'two' ]

  

The most common method of calling is unfortunate because it causes the declared function to be global by default. we all know that global members are not the best practices for programming. this is especially true in JavaScript. You will not regret it if you avoid using global members in JavaScript.

JavaScript function call Rule 1

In a function that is not directly called by specifying the owner object, such as myFunction (), the value of this becomes the default object (window in the browser ).

Function call
Now let's create a simple object and use the makeArray function as its method. We will use the json method to declare an object. We will also call this method.

 

//creating the objectvar arrayMaker = {    someProperty: 'some value here',    make: makeArray};//invoke the make() methodarrayMaker.make('one', 'two');// => [ arrayMaker, 'one', 'two' ]// alternative syntax, using square bracketsarrayMaker['make']('one', 'two');// => [ arrayMaker, 'one', 'two' ]

  


The difference here is that the value of this is changed to the object itself. you may wonder why the original function definition has not changed. Why is it not a window. well, this is how the function is passed in jsavacrip. the function is a standard data type in JavaScript, which is actually an object. you can pass them or copy them. as if the list of function associated parameters and function bodies are copied and assigned to the make attribute in arrayMaker, it is like defining an arrayMaker as follows:


var arrayMaker = {    someProperty: 'some value here',    make: function (arg1, arg2) {        return [ this, arg1, arg2 ];    }};

  

JavaScript function call Rule 2

In a method call syntax, such as obj. myFunction () or obj ['myfunction'] (), the value of this is obj.

This is the main source of bugs in event processing code. Let's take a look at these examples.

<input type="button" value="Button 1" id="btn1"  /><input type="button" value="Button 2" id="btn2"  /><input type="button" value="Button 3" id="btn3"  onclick="buttonClicked();"/><script type="text/javascript">function buttonClicked(){    var text = (this === window) ? 'window' : this.id;    alert( text );}var button1 = document.getElementById('btn1');var button2 = document.getElementById('btn2');button1.onclick = buttonClicked;button2.onclick = function(){   buttonClicked();   };</script>

  

Clicking the first button will display "btn" because it is a method call and this is the object to which it belongs (Button element) clicking the second button will display "window" because buttonClicked is directly called (unlike obj. buttonClicked ().) this is the same as our third button, which places the event handler function directly in the tag. therefore, the result of clicking the third button is the same as that of the second button.
Using JS libraries like jQuery has the following advantages: When jQuery defines an event processing function, the JS library will help override the value of this to ensure that it contains references to the current event source element,

// Use jQuery
$ ('# Btn1'). click (function (){
Alert (this. id); // jQuery ensures 'eas' will be the button
});

How does jQuery reload the value of this? Continue reading

The other two are apply () and call ()
The more JavaScript Functions you use, the more you will find that you need to pass functions and call them in different contexts, just like what Qjuery does in the event processing function, you often need to reset the value of this. remember what I told you. In Javascript, functions are also objects. Function objects contain predefined methods. Two of them are apply () and call (), we can use them to reset this.

var gasGuzzler = { year: 2008, model: 'Dodge Bailout' };makeArray.apply( gasGuzzler, [ 'one', 'two' ] );// => [ gasGuzzler, 'one' , 'two' ]makeArray.call( gasGuzzler,  'one', 'two' );// => [ gasGuzzler, 'one' , 'two' ]

  

These two methods are similar. The difference is the difference between the following parameters, Function. apply () uses an array to pass to the Function, and Function. call () is to pass these parameters independently. In practice, you will find that apply () is more convenient in most cases.

JSavacript function call rule 3

If we want to reload the value of this without copying a function to a method, we can use myFunction. apply (obj) or myFunction. call (obj ).

Constructor
I don't want to study the type definition in Javascript in depth, but at this moment we need to know that there is no class in Javascript, and any custom type requires an initialization function, defining Your type using a prototype object (as an attribute of the initialization function) is also a good concept. Let's create a simple type.
// Declare a constructor


Function ArrayMaker (arg1, arg2) {this. someProperty = 'whatever'; this. theArray = [this, arg1, arg2];} // declare the instantiation method ArrayMaker. prototype = {someMethod: function () {alert ('memethod called');}, getArray: function () {return this. theArray; }}; var am = new ArrayMaker ('one', 'two'); var other = new ArrayMaker ('first', 'second'); am. getArray (); // => [am, 'one', 'two']

  

It is very important and worth noting that the new operator appeared before the function call. Without that, your function is like a global function, and all the attributes we created will be created on the Global Object (window), and you don't want to do that. Another topic is that there is no return value in your constructor, so if you forget to use the new operator, some of your variables will be assigned undefined. for this reason, the constructor function is a good habit of starting with an uppercase letter, which serves as a reminder so that you do not forget the new operator before calling it.
With such caution, the code in the initialization function is similar to the initialization function you write in other languages. The value of this will be the object you will create.

Javascript function call Rule 4

When you use a function as the initialization function, for example, MyFunction (), the Javascript runtime will specify the value of this as the new object.

I want to understand that different function call methods will keep your Sjavacript code away from the bugs. Some such bugs will ensure that you always know the value of this is to avoid their first step.

Related Article

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.