JavaScript, 5 ways to call a function

Source: Internet
Author: User
Tags uppercase letter



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">functionmakeArray(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‘, ‘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‘ ]





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 objectvararrayMaker = {    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‘ ]









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 = {&NBSP;&NBSP;&NBSP;&NBSP;someproperty: ' some value here '&NBSP;&NBSP;&NBSP;&NBSP;MAKE:&NBSP;function (arg1, arg2) {&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;return [&NBSP;this&NBSP;&NBSP;&NBSP;&NBSP;};







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">functionbuttonClicked(){    vartext = (this=== window) ? ‘window‘: this.id;    alert( text );}varbutton1 = document.getElementById(‘btn1‘);varbutton2 = 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.

Using jquery
$ (' #btn1 '). Click (function () {
alert (this.id); JQuery ensures ' This ' 'll 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 < Code class= "JavaScript plain" >gasguzzler = {year:2008, model: ' Dodge Bailout ' };makearray.apply (Gasguzzler, [ ,&NBSP;"n" //= = [Gasguzzler, ' one ', ' one ', ' "]makearray.call (gasguzzler,  ,&NBSP;' " < Code class= "JavaScript Plain");//= = [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
Declaring a constructor





functionArrayMaker(arg1, arg2) {    this.someProperty = ‘whatever‘;    this.theArray = [ this, arg1, arg2 ];}// 声明实例化方法ArrayMaker.prototype = {    someMethod: function() {        alert( ‘someMethod called‘);    },    getArray: function() {        returnthis.theArray;    }};varam = newArrayMaker( ‘one‘, ‘two‘);varother = newArrayMaker( ‘first‘, ‘second‘);am.getArray();// => [ am, ‘one‘ , ‘two‘ ]








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.



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



JavaScript, 5 ways to call 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.