#1EasyJavaScript functions
1. Function.prototype.bind
JavaScriptClosures & Scope
Implement your own Function.prototype.bind without calling the native bind method. To avoid overwriting the actual Function.prototype.bind, implement the function as Function.prototype.myBind.
Example 1:
const john = {
age: 42,
getAge: function () {
return this.age;
},
};
const unboundGetAge = john.getAge;
console.log(unboundGetAge()); // undefined
const boundGetAge = john.getAge.myBind(john);
console.log(boundGetAge()); // 42Example 2 (Partial Application):
function add(a, b) {
return this.base + a + b;
}
const addTen = add.myBind({ base: 10 }, 5);
console.log(addTen(3)); // 18solution.js
Binds thisArg for object method (john.getAge)
(() => {
const john = {
age: 42,
getAge: function () {
return this.age;
},
};
const unboundGetAge = john.getAge;
expect(unboundGetAge()).toBe(undefined);
const boundGetAge = john.getAge.myBind(john);
expect(boundGetAge()).toBe(42);
})()