InterviewSolution
| 1. |
Explain ”this” with call, apply and bind in JavaScript? |
|
Answer» One of the main use of “call” is to change an array like object to array. There is an array like object arguments available for every normal function(not arrow function). It is very useful in functions, as we can get the number of arguments passed to it. Let’s convert the arguments into array, because arrays have a lots of functionality. Consider the below example, where we console log arguments. If we expand it in dev console, it shows it’s not and array and it’s __proto__ doesn’t have array functionalities. let sumNumbers = function() { console.log(arguments); } sumNumbers(1, 2, 3, 4);Now to convert it we will take an empty array and use it’s slice method. Then call it through call, by passing the argument Object. Now it is CONVERTED into array and the __proto__ have all array functionalities. So, we are using the array reduce method available to do the SUM of the number of arguments passed to it. let sumNumbers = function() { const argsToArray = [].slice.call(arguments); console.log(argsToArray); return argsToArray.reduce((acc, curr) => acc + curr); } console.log(sumNumbers(1, 2, 3, 4)); //10 console.log(sumNumbers(1, 2, 3)); //6The second application of call is in inheritance , using constructor functions. Consider the below example. Here in the Cat function, we CALLED its parent Mammal using call method with “this” of Cat. let Mammal = function(legs) { this.legs = legs; } let Cat = function(legs, isDomesticated) { Mammal.call(this, legs); this.isDomesticated = isDomesticated; } let tiger = new Cat(4, false); let homeCat = new Cat(4, true); console.log(tiger); // { legs: 4, isDomesticated: false } console.log(homeCat); // { legs: 4, isDomesticated: true }One of the practical use of apply is to pass an array to a function, which expects arguments only. Consider the case of Math.max, which gives the maximum of the arguments passed. So, now to pass an array like in below code, we convert it through apply. Note the first argument is null because we are not passing any Object for “this” binding. let arr = [20, 6, 29, 12]; console.log(Math.max(20, 6, 29, 12)); // 29 console.log(Math.max.apply(null, arr)); // 29One of the practical use of bind is in React. In React whenever we call a function from render(), we have to bind it’s “this” in constructor. Consider the below code. We bind the “this” of the event handler to the component instance in the constructor, we can pass it as a callback without worrying about it losing its context. class Foo extends React.Component{ constructor( props ){ super( props ); this.state = { text: '' }this.handleChange = this.handleChange.bind(this); } handleChange(event){ this.setState({ text: event.target.value }) } render(){ return ( <input type="text" value={this.state.text} onChange={this.handleChange} /> ); } } ReactDOM.render( <Foo />, document.getElementById("app") ); |
|