bind() method - Hard binding
bind() method creates a new function that will have "this" set to the parameter passed to bind.
bind() method is used when we want "this" value to be predictable
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function displayName() { | |
console.log(this.name); | |
} | |
var obj1 = {name: "Deepak"}; | |
var obj2 = {name: "Chetan"}; | |
var orig = displayName; | |
var displayName = function() { | |
orig.call(obj1); | |
}; | |
displayName(); // "Deepak" | |
displayName.call(obj2); // "Deepak" |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function bind2(fun, obj) { | |
return function() { | |
fun.call(obj); | |
}; | |
} | |
function displayName() { | |
console.log(this.name); | |
} | |
var obj1 = {name: "Deepak"}; | |
var obj2 = {name: "Chetan"}; | |
var displayName = bind2(displayName, obj1); | |
displayName(); // "Deepak" | |
displayName.call(obj2); // "Deepak" |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
if(!Function.prototype.bind2) { | |
Function.prototype.bind2 = function(obj) { | |
var fun = this; | |
return function() { | |
fun.apply(obj, arguments); | |
}; | |
}; | |
} | |
function displayName(lastName) { | |
console.log(this.name + " " + lastName); | |
} | |
var obj1 = {name: "Deepak"}; | |
var obj2 = {name: "Chetan"}; | |
var displayName = displayName.bind2(obj1); | |
displayName("Sisodiya"); // "Deepak Sisodiya" | |
displayName.call(obj2, "Sisodiya"); // "Deepak Sisodiya" |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function displayName(lastName) { | |
console.log(this.name + " " + lastName); | |
} | |
var obj1 = {name: "Deepak"}; | |
var obj2 = {name: "Chetan"}; | |
var displayName = displayName.bind(obj1); | |
displayName("Sisodiya"); // "Deepak Sisodiya" | |
displayName.call(obj2, "Sisodiya"); // "Deepak Sisodiya" |
Link 1 - Hard binding
Link 2 - Hard binding
Link 3 - Hard binding
Link 4 - Hard binding
No comments:
Post a Comment