5 ways to call functions from JavaScript

Source: Internet
Author: User

Tags: str function Racket Mode function use Method learning prototype

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.

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

The most common method, but unfortunately, global function calls when we learn javascript, we learn how to define functions using the syntax in the example Above. , we also know that invoking this function is very simple and we need to do just that:

1234567891011121314 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

123456789101112 //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‘ ]


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:

123456 var arraymaker = {     someproperty: ,     make: function (arg1, arg2) {          return [ this     };


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

123456789101112131415 <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 ' 'll be the butt on});
How does jquery overload the value of this? Continue reading

Two more: 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, just as Qjuery did in the event Handler. You often need to reset the value of This. remember what I told you, in javascript, a function is an object, and a function object contains some predefined methods, two of which are apply () and call (), which we can use to reset This.

12345 vargasGuzzler = { 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 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 this point we need to know that there are no classes in javascript, and that any one custom type requires an initialization function that uses the prototype object (as a property of the initialization Function) Defining your type is also a good doctrine, let's create a simple type//declare a constructor

12345678910111213141516171819 function ArrayMaker(arg1, arg2) {    this.someProperty = ‘whatever‘;    this.theArray = [ this, arg1, arg2 ];}// 声明实例化方法ArrayMaker.prototype = {    someMethod: function () {        alert( ‘someMethod called‘);    },    getArray: function () {        return this.theArray;    }};var am = new ArrayMaker( ‘one‘, ‘two‘ );var other = new ArrayMaker( ‘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.

5 ways to call functions from JavaScript

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.

Tags Index: