Function Binding
Advanced Functions: Function Binding
What is function binding in JavaScript?
View Answer:
Interview Response: Function binding in JavaScript is the process of tying a function to an object context, ensuring it uses that context as its 'this' value when called.
Code Example:
let dog = {
name: "Rover",
sound: "Woof",
makeSound: function() {
console.log(this.sound);
}
};
let cat = {
name: "Whiskers",
sound: "Meow"
};
// Bind makeSound function from dog to cat
let catSound = dog.makeSound.bind(cat);
catSound(); // Output: Meow
What are the three types of function binding techniques?
View Answer:
Interview Response: IThree function binding techniques are implicit binding (using object method), explicit binding (with call, apply, or bind), and constructor binding (new keyword for creating objects).
Code Example:
1. Default Binding:
function sayHello() {
console.log(this.message);
}
// A global variable
message = "Hello, World!";
sayHello(); // Output: "Hello, World!"
2. Implicit Binding:
let obj = {
message: "Hello, Object!",
sayHello: function() {
console.log(this.message);
}
}
obj.sayHello(); // Output: "Hello, Object!"
3. Explicit Binding (using call()):
function sayHello() {
console.log(this.message);
}
let obj = {
message: "Hello, Explicit!"
}
sayHello.call(obj); // Output: "Hello, Explicit!"
How does the bind() method work in JavaScript?
View Answer:
Interview Response: The bind() method creates a new function that, when called, has its 'this' keyword set to the provided value, with a given sequence of arguments preceding any others.
Code Example:
let person1 = {
name: 'John',
hello: function() {
console.log(`Hello, my name is ${this.name}.`);
}
};
let person2 = {
name: 'Sarah'
};
let sarahSayHello = person1.hello.bind(person2);
sarahSayHello(); // outputs: "Hello, my name is Sarah."
What are the advantages of using the bind() method?
View Answer:
Interview Response: The bind() method allows for explicit function context setting, function reuse with different objects, and partial application (pre-setting some arguments), improving code flexibility and reusability.
Code Example:
let car1 = {
brand: 'Tesla',
getBrand: function(){
console.log(this.brand);
}
};
let car2 = {
brand: 'Ford'
};
// Create a new function with 'this' set to car2
let getCar2Brand = car1.getBrand.bind(car2);
getCar2Brand(); // Output: 'Ford'
// Partial application
function multiply(x, y) {
return x * y;
}
let double = multiply.bind(null, 2); // 'this' is irrelevant here, so set to null
console.log(double(5)); // Output: 10
What is constructor binding in JavaScript?
View Answer:
Interview Response: Constructor binding is when a function is used as a constructor with the 'new' keyword, causing 'this' to refer to the newly created object.
Code Example:
function Car(brand) {
this.brand = brand;
this.getBrand = function() {
console.log(this.brand);
};
}
let car = new Car('Tesla');
car.getBrand(); // Output: 'Tesla'
Can you explain what explicit function binding is in JavaScript?
View Answer:
Interview Response: Explicit function binding in JavaScript lets you set "this" value for a function using call, apply, or bind, allowing greater control over function execution context.
Technical Response: Window, Implicit, and Explicit function binding are JavaScript's three types of binding strategies. Explicit binding compels a function call to bind to a specific context object by utilizing call, apply, or bind. These predefined JavaScript methods get passed down to all functions via the function prototype. Functions have a method bind that allows us to fix "this." Binding is the ideal option for tying the context to the correct object and preventing "this" from being lost.
Code Example:
let user = {
firstName: 'John',
};
function func() {
console.log(this.firstName);
}
let funcUser = func.bind(user);
funcUser(); // John
Can you explain what implicit function binding is in JavaScript?
View Answer:
Interview Response: Implicit binding occurs when a function is called as a method of an object, and "this" automatically refers to the object before the dot.
Here's a simple code example:
let obj = {
name: 'John',
sayHello: function() {
console.log('Hello, ' + this.name);
}
};
obj.sayHello(); // outputs: "Hello, John"
In this example, when sayHello()
is invoked as a method of obj
(obj.sayHello()
), the this
inside sayHello
implicitly binds to obj
.
Can you explain the function of the bind() method?
View Answer:
Interview Response: The bind() method creates a new function with a specific "this" value, allowing you to control the context in which the original function is executed.
Technical Response: The bind method generates a new function that, when called, sets the "this" keyword to the provided value, with a specified sequence of arguments preceding any arguments provided when the new function gets invoked. Bind creates a new function that may be called later in the code while keeping the desired context binding.
Code Example:
Syntax: let boundFunc = func.bind(thisArg[, arg1[, arg2[, ...argN]]]);
Syntax: let boundFunc = func.bind(thisArg[, arg1[, arg2[, ...argN]]]);
const module = {
x: 42,
getX: function () {
return this.x;
},
};
const unboundGetX = module.getX;
console.log(unboundGetX()); // The function gets invoked at the global scope
// expected output: undefined
const boundGetX = unboundGetX.bind(module);
console.log(boundGetX());
// expected output: 42
note
This is useful for passing functions into other functions, like setTimeout(), which later invokes and won't necessarily bind the invoked function to the correct object without being coerced. The first parameter is the context object, and all other parameters are individually listed, like the call method.
What is a partial function application?
View Answer:
Interview Response: Partial function application means predefining some of a function's arguments, creating a new function that requires fewer arguments to execute the original logic.
Code Example:
function mul(a, b) {
return a * b;
}
let triple = mul.bind(null, 3);
console.log(triple(3)); // = mul(3, 3) = 9
console.log(triple(4)); // = mul(3, 4) = 12
console.log(triple(5)); // = mul(3, 5) = 15