How to Call Main Function Again Typescript
Functions in JavaScript tin be called in different ways. At showtime glance, that may seem like a crazy statement. How tin can there be more than one way to call a part? Don't we just call information technology?
Well, dear reader, as we shall discuss in this post, at that place are 4 means to phone call a function in JavaScript. Your detail scenario will make up one's mind which one to utilise. Additionally, each method will dictate the value of "this", also known every bit the context, inside the function.
A point to go along in mind
Whenever a function is chosen in JavaScript, regardless of how information technology is called, two implicit arguments are passed to information technology. Those 2 implicit arguments are this, the context in which the function will execute and the arguments parameter. The arguments parameter is an array-like construction containing whatsoever passed arguments. Its "array-like" but it is not an array.
Now, without farther ado, let'south introduce the 4 ways in which a office tin exist called.
JavaScript functions can be called:
- Every bit a function
- As a method
- As a constructor
- via telephone call and apply
Let's look at each one.
Calling a office as a function
Since the creation of the language, this is probably the mode most functions have been called: equally a function. If you've ever placed a snippet of JavaScript on a web page and called it from a push click, y'all take called a JavaScript function as a function. Let'south await at a code sample.
<push onclick="sayHello()">say hello</button> <script> part sayHello() { console.log(this); console.log(arguments); console.log('hi'); } </script> In this simple code example, we have a push that when clicked, calls the sayHello() function. Inside the function, nosotros log the value of this followed bu the value of arguments. Then we say hello. Let's see what nosotros make it the console when we click the button.
As you lot can meet, the value of this is the Window object. That is the context in which our nifty footling part is executing. You do take the option to force the context of this to be undefined in this instance. To do then, you simply add the 'use strict'; directive to your lawmaking.
<button onclick="sayHello()">say hello</push button> <script> 'use strict'; //strength the context to be undefined part sayHello() { console.log(this); console.log(arguments); console.log('hello'); } </script> The arguments parameter in this instance does not have any values since no parameters were passed to the function.
Calling a role equally a method
In society to call a function as a method, it must be defined every bit a property on an object. Allow's look at some code.
<push button onclick="greeter.sayHello()">say hello</button> <script> greeter = { sayHello: function () { console.log(this); panel.log(arguments); console.log('howdy'); } } Here y'all tin run into that we have wrapped the sayHello() office inside an object called greeter thus making information technology a property on that object. We then update our onclick handler to phone call it using the object dot syntax: greeter.sayHello()
When we phone call the office in this way, here is what nosotros get in the console:
Hither we see that the context of the this argument points to the greeter object. This makes more than sense than the global window object. As expected, we still have access to the arguments parameter as well.
Calling a part as a constructor
Before we look at the code for calling a role equally a constructor, allow's take a moment and consider the purpose of a constructor. A constructor is meant to set upwardly some initial state within an object. To construct it. That existence the case, this is a more specialized case of how to call a function. Nosotros are calling this function with the intent of creating something new and getting information technology back. Let's look at a code sample.
<input blazon="text" id="name"></input> <button onclick="sayHello()">say how-do-you-do</push button> <script> function Greeter(name) { console.info('begin constructor'); console.log(this); console.log(arguments); this.name = name; console.info('cease constructor') } function sayHello() { var name = document.getElementById('proper name').value; var grtr = new Greeter(proper noun); panel.log('hello ' + grtr.name); } </script> In this case, we accept added an input text box so that the user tin enter their name. It'south not really a proper greeting without a name. Once once again, when our button is clicked we telephone call the sayHello() part. In our sayHello function, we grab the value in the text box and create a new instance of the Greeter object by calling new Greeter().
The new keyword and the upper-case letter G make information technology clear that this office is existence called as a constructor. When a function is chosen in this way, this is prepare to the newly created object. We then add a name property to the newly created object and set its value to the parameter that was passed to the constructor. The newly created object is passed dorsum to the calling lawmaking and saved in the grtr variable. Finally, in the call to console.log, we admission the name property that we simply ready on the Greeter object.
Calling a function via phone call and apply
One matter to always keep in mind when working with functions in JavaScript is that they are kickoff-class objects. That means that a function can have its ain properties and its own methods. Yes, you read that correctly. A function can have its own methods. The call and apply methods are two of those methods. The call and use methods allow you lot to specify the context in which the function will execute. They allow you to set the this value. Permit's take a look at a lawmaking example.
<push button onclick="go()">Get</button> <script> var people = []; var name = 'alex'; function Person(idx) { idx % ii === 0 ? this.name = 'alex ' + idx : this.name = 'bob ' + idx; } role printName() { console.log(this.name); } function get() { //call printName to print the proper name variable defined on the window object printName(); //populate the people array with a couple of people for (let idx = 0; idx < 5; idx++) { people.push button(new Person(idx)); } // lets phone call the printName for each object that we only created // seting this dynamically people.forEach(p => { printName.phone call(p); }); // printName.telephone call(valueOfThis, 1, 2, three); // printName.utilise(valueOfThis, [i, 2, 3]) } </script> In this code, we showtime by defining a couple of variables. An empty assortment that we will populate with a couple of Person objects and a name. We then take the constructor for the Person object. All it does is cull a name based on the index that is passed to it.
Side by side, we accept the printName() function. Information technology only prints any value is in the proper noun variable of whatsoever object is set to the current context. And finally, we have the get() role that is executed when the user presses the push button.
The first affair we practice when the button is clicked is call printName() directly. If you recall from before in this mail service, this is calling a role equally a function. Equally a issue, the context is the global window object and the name 'alex' is printed to the console. So far, then adept.
Adjacent, we set up a for loop and create 5 Person objects and push them into the people array.
Then we jump right into an assortment.forEach on our people array. During each iteration, we call printName.phone call() passing the current object as the context. This means that we are setting the context of the function dynamically. Pretty cool. This produces the post-obit output in the panel.
The first 'alex' in the output is from our earlier call to printName(). Each additional line of output is from iterating over the array.
This code demonstrates the call() method available on all functions. It looks very similar to object dot syntax because it is object dot syntax. All functions in JavaScript are objects.
The use method is very similar. The only departure between the two is the arguments they accept. telephone call() accepts a list of values while apply() accepts an array, like so:
//telephone call accepts a list of values printName.call(valueOfThis, 1, 2, 3); //apply accepts an array of values printName.apply(valueOfThis, [1, 2, 3]); That wraps upwardly this quick introduction of the 4 ways to call a JavaScript function. I find that I employ all of these methods and knowing what'due south happening under the hood is really helpful.
Go along in mind that in JavaScript, functions are first-course objects. They can take their own properties and methods and can be passed around just like other objects. This concept of functions as objects can accept a chip of getting used to if you're coming from another language like C# or Java. I know it took me a little bit to go my head wrapped around it.
Cheers for reading.
stonehavenmants1960.blogspot.com
Source: http://www.ritzcovan.com/index.php/2019/12/11/4-ways-to-call-a-function-in-javascript/
0 Response to "How to Call Main Function Again Typescript"
Post a Comment