Grokking Call(), Apply() and Bind() Methods in JavaScript

These functions are very important for every JavaScript Developer and are used in almost every JavaScript Library or Framework. Check out the code snippet below.

Taken from the very popular library Lodash

/**
	* Creates a function that invokes `func` with arguments reversed.
	*
	* @since 4.0.0
	* @category Function
	* @param {Function} func The function to flip arguments for.
	* @returns {Function} Returns the new flipped function.
	* @see reverse
	* @example
	*
	* const flipped = flip((...args) => args)
	*
	* flipped('a', 'b', 'c', 'd')
	* // => ['d', 'c', 'b', 'a']
	*/
	function flip(func) {
	  if (typeof func !== 'function') {
	    throw new TypeError('Expected a function')
	  }
	  return function(...args) {
	    return func.apply(this, args.reverse())
	  }
	}

	export default flip

Look at the statement on line 21, return func.apply(this, args.reverse())

In this article, we will have a look at the call()apply() and bind() methods of JavaScript. Basically these 3 methods are used to control the invocation of the function. The call() and apply() were introduced in ECMAScript 3 while bind() was added as a part of ECMAScript 5.

Let us start with an example to understand these.

Suppose you are a student of X university and your professor has asked you to create a math library, for an assignment, which calculates the area of a circle.

const calcArea = {
	  pi: 3.14,
	  area: function(r) {
	    return this.pi * r * r;
	  }
	}

calcArea.area(4); // prints 50.24


You test this and verify its result, it is working fine and you upload the library to portal way before the deadline ends. Then you ask your classmates to test and verify as well, you come to know that that your result and their results mismatches the decimals precision. You check the assignment guidelines, Oh no! The professor asked you to use a constant **pi** with 5 decimals precision. But you used **3.14** and not **3.14159** as the value of pi. Now you cannot re-upload the library as the deadline date was already over. In this situation, **call()** function will save you.

#js #javascript-development #javascript #javascript-interview #javascript-tips

What is GEEK

Buddha Community

Grokking Call(), Apply() and Bind() Methods in JavaScript
Tanya  Shields

Tanya Shields

1594896120

JavaScript tutorial - call, apply and bind methods in JavaScript

Working with JavaScript “this” keyword can be tricky. Not knowing the background rules may end up with the famous “it works, but I don’t know why” or worse: “it doesn’t work and I don’t know why”. It’s good to know the theory before putting things into practice. Call(), Apply() and Bind() methods can come in handy when setting the “this” value.
This tutorial covers call(), apply() and bind() methods. A multiple basic examples have been provided.

Basic rules worth remembering:

  1. “this” always refers to an object.
  2. “this” refers to an object which calls the function it contains.
  3. In the global context “this” refers to either window object or is undefined if the ‘strict mode’ is used.
var car = { 
    registrationNumber: "GA12345",
    brand: "Toyota",

    displayDetails: function(){
        console.log(this.registrationNumber + " " + this.brand);
    }
}

The above will work perfectly fine as long as we use it this way:

car.displayDetails(); // GA12345 Toyota

But what if we want to borrow a method?

var myCarDetails =  car.displayDetails;
myCarDetails();

Well, this won’t work as the “this” will be now assigned to the global context which doesn’t have neither the registrationNumber nor the brand property.

#javascript #programming #call #apply #bind methods

Grokking Call(), Apply() and Bind() Methods in JavaScript

These functions are very important for every JavaScript Developer and are used in almost every JavaScript Library or Framework. Check out the code snippet below.

Taken from the very popular library Lodash

/**
	* Creates a function that invokes `func` with arguments reversed.
	*
	* @since 4.0.0
	* @category Function
	* @param {Function} func The function to flip arguments for.
	* @returns {Function} Returns the new flipped function.
	* @see reverse
	* @example
	*
	* const flipped = flip((...args) => args)
	*
	* flipped('a', 'b', 'c', 'd')
	* // => ['d', 'c', 'b', 'a']
	*/
	function flip(func) {
	  if (typeof func !== 'function') {
	    throw new TypeError('Expected a function')
	  }
	  return function(...args) {
	    return func.apply(this, args.reverse())
	  }
	}

	export default flip

Look at the statement on line 21, return func.apply(this, args.reverse())

In this article, we will have a look at the call()apply() and bind() methods of JavaScript. Basically these 3 methods are used to control the invocation of the function. The call() and apply() were introduced in ECMAScript 3 while bind() was added as a part of ECMAScript 5.

Let us start with an example to understand these.

Suppose you are a student of X university and your professor has asked you to create a math library, for an assignment, which calculates the area of a circle.

const calcArea = {
	  pi: 3.14,
	  area: function(r) {
	    return this.pi * r * r;
	  }
	}

calcArea.area(4); // prints 50.24


You test this and verify its result, it is working fine and you upload the library to portal way before the deadline ends. Then you ask your classmates to test and verify as well, you come to know that that your result and their results mismatches the decimals precision. You check the assignment guidelines, Oh no! The professor asked you to use a constant **pi** with 5 decimals precision. But you used **3.14** and not **3.14159** as the value of pi. Now you cannot re-upload the library as the deadline date was already over. In this situation, **call()** function will save you.

#js #javascript-development #javascript #javascript-interview #javascript-tips

Annalise  Hyatt

Annalise Hyatt

1598947500

Binding Concept in Javascript

Javascript binding is done using the Bind() method. With the help of the bind method, we can make one common function and bind different objects, so that the function gives different results when its need. otherwise, it gives the same result or gives an error while the code is executing.

In short, when a function or method is invoked, the bind() method allows us to easily set which object will be bound by this keyword.

var info= {

name : "XYZ",
printFunc: function(){
document.write(this.name);} // XYZ
}
info.printFunc();

In the above example, there is no problem accessing the name, this keyword bind the name variable to the function. This is called as default binding.

This keyword will here point to object i.e info object.

var info = {

name : "XYZ",
printFunc: function(){
    document.write(this);// window object or undefined(strict mode).
    document.write(this.name);
  }
}
var printFunc2= info.printFunc;
printFunc2();

In the above example, we are storing a reference of info.printFunc to printFunc2 variable. After that, we are calling it without an object reference, so this will now refer to the window (global) object or undefined (in strict mode). Hence, the binding of this is lost, so no output is produced.

So basically, the Bind() method is used so that binding of this is not lost.

By using bind() method we can set the context of _this or in simple terms we can bind this _to a particular object.


How to use bind?

  1. The bind() method creates a new function, when invoked, has the this sets to the provided value. See example below:-
var car1 = {
  name : "swift",
  color: "red",
}
var car2 = {
  name : "alto",
  color: "blue",
}
function infoFunc() {
   document.write(this.name + " " + this.color + "<br/>");
 }
infoFunc.bind(car1)(); // swift red
infoFunc.bind(car2)(); // alto blue

There is one common function infoFunc() which is invoked 2times with different objects so that different results are produced. This first binds to car1 object and then to car2 object.

2. Function borrowing which means the bind() allows an object to borrow a method from another object without making a copy of that method.

#this-keyword #binding #javascript #front-end-development #call-apply-bind

Rahul Jangid

1622207074

What is JavaScript - Stackfindover - Blog

Who invented JavaScript, how it works, as we have given information about Programming language in our previous article ( What is PHP ), but today we will talk about what is JavaScript, why JavaScript is used The Answers to all such questions and much other information about JavaScript, you are going to get here today. Hope this information will work for you.

Who invented JavaScript?

JavaScript language was invented by Brendan Eich in 1995. JavaScript is inspired by Java Programming Language. The first name of JavaScript was Mocha which was named by Marc Andreessen, Marc Andreessen is the founder of Netscape and in the same year Mocha was renamed LiveScript, and later in December 1995, it was renamed JavaScript which is still in trend.

What is JavaScript?

JavaScript is a client-side scripting language used with HTML (Hypertext Markup Language). JavaScript is an Interpreted / Oriented language called JS in programming language JavaScript code can be run on any normal web browser. To run the code of JavaScript, we have to enable JavaScript of Web Browser. But some web browsers already have JavaScript enabled.

Today almost all websites are using it as web technology, mind is that there is maximum scope in JavaScript in the coming time, so if you want to become a programmer, then you can be very beneficial to learn JavaScript.

JavaScript Hello World Program

In JavaScript, ‘document.write‘ is used to represent a string on a browser.

<script type="text/javascript">
	document.write("Hello World!");
</script>

How to comment JavaScript code?

  • For single line comment in JavaScript we have to use // (double slashes)
  • For multiple line comments we have to use / * – – * /
<script type="text/javascript">

//single line comment

/* document.write("Hello"); */

</script>

Advantages and Disadvantages of JavaScript

#javascript #javascript code #javascript hello world #what is javascript #who invented javascript

Understanding Call(), Bind() & Apply() Methods in JavaScript In Simplest Way!

Hello everyone! In this article, we shall try to understand the functionalities of JavaScript methods call()bind(), and apply().

In order to make it simpler for everyone, we shall be trying to understand them with the help of a simple example. Also, I shall make sure to not use tech-heavy jargon, so that even the new learners may understand the working of these methods easily without having to wrap their head around other stuff.

Additionally, I shall not be putting the code in a text editor or GitHub link so as to encourage you guys to code along as you read. It would really help you a lot, trust me on this. So, without any further ado, let’s get started.

First of all, let’s take a look at the basic example that we are going to follow. Here, we have created an object for an employee record, in which, we’ll be storing their basic information. Additionally, we’ll be setting up a method that can increment the salary of the employee by 10000.

Note: The “this” keyword is referring to the object in which it is situated. If it was used outside of the object, it would have referred to the window object.

#binding #programming #javascript #coding