Skip to content

Instantly share code, notes, and snippets.

@ivan-ha
Created March 1, 2017 15:31
Show Gist options
  • Save ivan-ha/0a135ef3cc91e32b3ce58102e4eb4a10 to your computer and use it in GitHub Desktop.
Save ivan-ha/0a135ef3cc91e32b3ce58102e4eb4a10 to your computer and use it in GitHub Desktop.
Usage of call(), apply(), bind() in js
var person = {
firstname: 'John',
lastname: 'Doe',
getFullName: function() {
return this.firstname + ' ' + this.lastname;
}
}
var logName = function(arg1, arg2) {
console.log('Logged: ' + this.getFullName());
console.log('Arguments: ' + arg1 + ' ' + arg2);
}
var logPersonName = logName.bind(person); // bind() will copy the function and invoke later
logPersonName('en');
logName.call(person, 'en', 'es'); // call() pass argument normally and invoke immediately
logName.apply(person, ['en', 'es']); // apply() pass argument as an array and invoke immediately
/****** FUNCTION BORROWING ******/
// calling function from a scope but provide it with another 'this'
var person2 = {
firstname: 'Foo',
lastname: 'Bar'
}
console.log(person.getFullName.apply(person2)); // print 'Foo Bar'
/****** FUNCTION CURRYING ******/
// hardcode some arguments for a function call
function multiply(a, b) {
return a * b;
}
var multipleByTwo = multiply.bind(this, 2);
console.log(multipleByTwo(4)); // print '8'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment