Skip to content

Instantly share code, notes, and snippets.

@cortesben
Last active March 28, 2017 01:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cortesben/818e1c91a6c5399c36449bcba543f858 to your computer and use it in GitHub Desktop.
Save cortesben/818e1c91a6c5399c36449bcba543f858 to your computer and use it in GitHub Desktop.
Bind and call
let person1 = {
name: 'Ben'
}
let person2 = {
name: 'Christina'
}
function logName() {
return this.name;
}
console.log(logName());
// returns an undefined
console.log( logName.bind(person1)() );
// call function bind object and call function
console.log( logName.bind(person2)() );
let number = {
x: 24,
y: 22
}
let count = function() {
console.log(this.x + this.y); //no this context here
}
count();
let boundCount = count.bind(number);
boundCount();
let obj = {
num: 2
}
let addToThis = function(a, b, c) {
return this.num + a + b + c;
}
// call binds the function to the first object passed in
// parameter are passed in subsequent values
console.log(addToThis.call(obj, 1, 2, 3));
let person1 = {
firstName : 'Jack',
lastName: 'Davis'
}
let person2 = {
firstName : 'Mark',
lastName: 'Price'
}
function hello(greeting) {
console.log(`${greeting} ${this.firstName} ${this.lastName}`);
}
hello.call(person1, 'Hello');
hello.call(person2, 'Fuck off!');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment