How JavaScript calls a function

Source: Internet
Author: User
Tags uppercase letter

Abstract: This article introduces in detail the methods and principles of various function calls in JavaScript, which are very helpful for understanding JavaScript functions.

Again and again, I found that the bug-coded JavaScript code was caused by the lack of a real understanding of how JavaScript functions work (by the way, many of those codes were 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, from the surface we think that those functions are very similar to the functions in C #, but we can see in a moment that there are still very important different places, 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 simply returns the current value of this and two supplied arguments.

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

The most common method, but unfortunately, a global function call
When we learned JavaScript, we learned how to use the syntax in the example above to define a function.
We also know that invoking this function is very simple, and we need to do just that:

Makearray (' One ', ' both ');/= = [window, ' One ', ' one ', ']wait a minute. What's that Windowalert (typeof window.methodthatdoesntexist);//= = Undefinedalert (typeof window.makearray);//= >window.makearray (' One ', ' one ', ' both ');/= = [window, ' One ', ' both ']

I say the most common invocation method is unfortunate because it causes the function we declare to be global by default. We all know that global membership is not a best practice for programming. This is especially true in JavaScript, and you won't regret it if you avoid using global members in JavaScript.

JavaScript function call Rule 1

In a function that is not directly called by the explicit owner object, such as MyFunction (), the value of this will be the default object (the window in the browser).

Function call
Let's now create a simple object, using the Makearray function as a method, we will use JSON to declare an object, we also call this method

Creating the Objectvar Arraymaker = {    Someproperty: ' Some value here ',    make:makearray};//invoke the Make () meth Odarraymaker.make (' One ', ' both ');/= = [Arraymaker, ' one ', ' one ', ']//alternative syntax, using square bracketsarraymake r[' Make ' (' One ', ' both ');//= = [Arraymaker, ' One ', ' both ']

See the difference here, the value of this becomes the object itself. You may wonder why the original function definition has not changed, why it is not a window. Well, that's how the function is passed in Jsavacript, which is a standard data type in JavaScript. Exactly is an object. You can pass them on or copy them. It's as if the entire function has both a list of parameters and a function body copied and assigned to the Arraymaker attribute make, which is like defining a arraymaker:

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

JavaScript function call Rule 2

In a method invocation syntax, like obj.myfunction () or obj[' myFunction '), this value is obj

This is the main source of the bug in the event handling code, and 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 on the first button will show "BTN" because it is a method call, this is the object (button element) to which 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 the result of clicking the third button is the same as the second one.
The advantage of using a JS library like jquery is 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.

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

How does jquery overload the value of this? Continue Reading


Two additional: Apply () and call ()
The more you use JavaScript functions, the more you will find that you need to pass functions and invoke them in different contexts, as Qjuery does in the event handler, and you often need to reset the value of this. Remember what I told you, In JavaScript, the function is also an object, and the function object contains some predefined methods, two of which are apply () and call (), which we can use to reset this.

var Gasguzzler = {year:2008, model: ' Dodge bailout '};makearray.apply (Gasguzzler, [' One ', ' both ']);/= = [Gasguzz Ler, ' One ', ' one ', ']makearray.call ' (Gasguzzler, ' One ', ' both '  );/= = [Gasguzzler, ' One ', ' both ']

The two methods are similar, different from the later 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 without duplicating the function to a method.

Constructors
I don't want to delve into the definition of type 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 that using a prototype object (as a property of the initialization function) to define your type is also a good doctrine, Let's create a simple type

Declares a constructor function Arraymaker (arg1, arg2) {    this.someproperty = ' whatever ';    This.thearray = [This, arg1, arg2];} Declares the instantiation method Arraymaker.prototype = {    somemethod:function () {        alert (' SomeMethod called ');    },    GetArray: function () {        return this.thearray;    }};  var am = new Arraymaker (' One ', ' one ', ' one '), var other = new Arraymaker (' first ', ' second '); Am.getarray ();/= [am, ' one ' , ' both ']

A very important and noteworthy thing is that the new operator appears in front of the function call, and 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 to do that, another topic, because there is no return value in your constructor, So if you forget to use the new operator, some of your variables will be assigned a value of undefined. For this reason, the constructor function starts with an uppercase letter as a good habit, which can be used as a reminder to not forget the previous new operator when calling.
With this 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 an initialization function, like MyFunction (), the JavaScript runtime assigns the value of this to the newly created object.

Summarize
I would like to understand that different function calls will keep your sjavacript code away from bugs, and some of these bugs will make sure you always know that the value of this is to avoid their first step function

All of this means that the method we previously called Makearray is the same as the method called below, the object doing there? Why is it the value of this? If you haven ' t stopped-think about it, please staywith me here.
Wait, what's that window object doing here, why this is the value of it, if you haven't stopped to think about it before, then please come with me to analyze it, in JavaScript, I do not refer to a particular browser, there is a global object, Each line of code that appears to be scattered in your script, such as a declaration outside an object, is actually written in the context of a global object. In our case, the Makearray function can be said to be not a loose global function, but a method of the global object, Let's go back and look at the browser, where its global objects are mapped to the Window object.

Author: The Source of the dream: the original link of the blog Park

How JavaScript calls a function

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.