Created
September 18, 2020 19:24
-
-
Save arnonate/2e4120df07f30ac45eaaac9d8028da86 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
// Use .bind() when you want that function to later be called | |
// with a certain context, useful in events. | |
// Use .call() or .apply() when you want to invoke the | |
// function immediately, with modification of the context. | |
// implement Function.prototype.bind() | |
/* | |
const foo = function() { | |
console.log(this.bar); | |
let baz = foo.bind({bar: 'hello}) | |
baz(); // Hello | |
} | |
*/ | |
function bindWithCall(fn, context) { | |
return function() { | |
fn.call(context, arg1, arg2); | |
}; | |
} | |
function bindWithApply(fn, context) { | |
return function() { | |
fn.apply(context, [arg1, arg2]); | |
}; | |
} | |
// Bind returns a Bound Function Object that, when called | |
// calls the wrapped function with bound context | |
var object = { x: 9 }; | |
var module = { | |
x: 18, | |
getX: function() { | |
return this.x; | |
} | |
}; | |
console.log(module.getX()); | |
var retrieveX = module.getX; | |
console.log(retrieveX()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment