Last active
March 28, 2017 01:01
-
-
Save cortesben/818e1c91a6c5399c36449bcba543f858 to your computer and use it in GitHub Desktop.
Bind and call
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
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(); |
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
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