Skip to content

Instantly share code, notes, and snippets.

@cortesben cortesben/bind.js
Last active Mar 28, 2017

Embed
What would you like to do?
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
You can’t perform that action at this time.