5 ways to invoke functions in JavaScript _javascript tips

Source: Internet
Author: User
Tags function definition

This article introduces in detail the various function calls in JavaScript and its principle, which is helpful to understand the function of JavaScript.

JavaScript, 5 ways to call a function

Again and again, I've found that the bug-coded JavaScript code is the result of not really understanding how JavaScript functions work (by the way, many of those codes are written by me). JavaScript has the feature of functional programming, and when we choose to face it, it will be a hindrance to our progress.

As a beginner, we're going to test the five methods of function invocation, and on the surface we think that those functions are very similar to functions in C #, but we can see that there are very important differences for a while, ignoring these differences will undoubtedly lead to bugs that are difficult to track. Let's start by creating a simple function that will be used in the next article, which returns only the current value of this and two supplied arguments.

Copy Code code as follows:

<script type= "Text/javascript" >
function Makearray (arg1, arg2) {
return [This, arg1, arg2];
}
</script>

Most commonly used methods, but unfortunately, global function calls
When we learn JavaScript, we learn how to use the syntax in the example above to define functions.
And we know it's very simple to call this function, and all we need to do is just:

Copy Code code as follows:

Makearray (' One ', ' two ');
=> [window, ' One ', ' two ']

Wait a minute. What ' s that window


Alert (typeof window.methodthatdoesntexist);
=> undefined
Alert (typeof Window.makearray);
=>


Window.makearray (' One ', ' two ');
=> [window, ' One ', ' two ']

I say the most common method of invocation is unfortunate because it causes the function we declare to be global by default. We all know that global members are not the best practice for programming. This is particularly true in JavaScript, and you won't regret it in JavaScript by avoiding the use of global members.

JavaScript function call Rule 1
in functions that are not called directly by an explicit owner object, such as MyFunction (), the value that causes this is the default object (the window in the browser).

Function call

Let's now create a simple object, using the Makearray function as one of its methods, we'll use JSON to declare an object, and we'll call this method

Copy Code code as follows:

Creating the Object
var arraymaker = {
Someproperty: ' Some value here ',
Make:makearray
};

Invoke the Make () method
Arraymaker.make (' One ', ' two ');
=> [Arraymaker, ' One ', ' two ']
Alternative syntax, using square brackets
arraymaker[' make '] (' One ', ' two ');
=> [Arraymaker, ' One ', ' two ']

See the difference here, the value of this becomes the object itself. You may be wondering why the original function definition did not change, and why it is not window. Well, that's how the function is passed in the Jsavacript, the function is a standard data type in JavaScript, Exactly an object. You can pass them on or copy them. It's like the whole function. The list of parameters and function bodies are copied and assigned to the attribute make in Arraymaker, which is like defining a arraymaker:

Copy Code code as follows:

var arraymaker = {
Someproperty: ' Some value here ',
Make:function (Arg1, arg2) {
return [This, arg1, arg2];
}
};

JavaScript function call Rule 2

In one use method call syntax, like obj.myfunction () or obj[' MyFunction '] (), at which point the value of this is obj

This is the main source of bugs in the event handling code, and look at these examples

Copy Code code as follows:

<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 on the first button will show "BTN" because it is a method call, this is the object (button element) Click the second button will display "window" because buttonclicked is called directly (unlike obj.buttonclicked ().) This is the same as our third button, where the event handler is placed directly in the label. So click on the third button and the result is the same as the second one.
Using a JS library like jquery has the advantage that when an event handler is defined in jquery, the JS library helps rewrite the value of this to ensure that it contains a reference to the current event source element.

Copy Code code as follows:

Using jquery
$ (' #btn1 '). Click (function () {
alert (this.id); JQuery ensures ' this ' would be the button
});

How does jquery overload the value of this? Continue Reading

The other two: apply () and call ()

The more you use JavaScript functions, the more you find that you need to pass functions and invoke them in different contexts, as qjuery do in the event handler, you often need to reset the value of this. Remember what I told you, Functions are also objects in JavaScript, and function objects contain predefined methods, two of which are apply () and call (), which we can use to reset this.

Copy Code code as follows:

var Gasguzzler = {year:2008, model: ' Dodge bailout '};
Makearray.apply (Gasguzzler, [' One ', ' two ']);
=> [Gasguzzler, ' One ', ' two ']
Makearray.call (Gasguzzler, ' one ', ' two ');
=> [Gasguzzler, ' One ', ' two ']

The two methods are similar, different from the following parameters, Function.apply () is used an array to pass to the function, and Function.call () is to pass these parameters independently, in practice you will find that apply () in most cases more convenient.

Jsavacript function Call Rule 3

We can use Myfunction.apply (obj) or myfunction.call (obj) if we want to overload the value of this if we do not copy the function to a method.

Construction device

I don't want to delve into the definition of types in JavaScript, but at the moment we need to know that there are no classes in JavaScript, and that any custom type requires an initialization function, and it's a good idea to use a prototype object (as an attribute of the initialization function) to define your type. Let's create a simple type

Copy Code code as follows:

Declaring a constructor
function Arraymaker (arg1, arg2) {
This.someproperty = ' whatever ';
This.thearray = [This, arg1, arg2];
}
Declaring the instantiation method
Arraymaker.prototype = {
Somemethod:function () {
Alert (' SomeMethod called ');
},
Getarray:function () {
return this.thearray;
}
};

var am = new Arraymaker (' One ', ' two ');
var other = new Arraymaker (' A ', ' second ');

Am.getarray ();
=> [AM, ' one ', ' two ']

A very important and noteworthy is the new operator that appears in front of the function call. Without that, your function is like a global function, and the attributes we create will be created on the Global Object (window), and you don't want that, and the other topic is, because there is no return value in your constructor, So if you forget to use the new operator, it will cause some of your variables to be assigned to undefined. For this reason, constructor functions begin with uppercase letters as a good habit, which can be used as a reminder that you should not forget the new operator before you call.

With such caution, the code in the initialization function is similar to the initialization function you write in other languages. This value will be the object you will create.

JavaScript function call Rule 4

When you use a function as an initialization function, like MyFunction (), the runtime of JavaScript will specify the value of this as the new object.

I would like to understand the different ways in which functions are invoked to keep your sjavacript code away from bugs, and some of these bugs will make sure 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.