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
const foo = { | |
bar: 'baz', | |
getBar: function() { // assigned as a property on an object, getBar is a method | |
console.log(this.bar); // the value of this here: foo | |
}, | |
}; | |
foo.getBar() // logs 'baz' | |
let qux = foo.getBar; // assigning the function getBar to the variable qux |
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
const foo = { | |
bar: 'baz', | |
getBar: function() { | |
console.log(this.bar); | |
}, | |
}; | |
let qux = foo.getBar; | |
qux.call(foo); // logs 'baz' |
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
const foo = { | |
bar: 10, | |
multiplyByBar: function(...args) { | |
args.forEach(arg => console.log(arg * this.bar)); | |
}, | |
}; | |
foo.multiplyByBar(5); // logs 50 | |
foo.multiplyByBar(5, 10, 15) // logs 50, then 100, then 150 |
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
const foo = { | |
bar: 10, | |
multiplyByBar: function(...args) { | |
args.forEach(function(arg) { | |
console.log(arg * this.bar); | |
}, this); | |
} | |
}; | |
const qux = foo.multiplyByBar.bind(foo); |
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
const foo = { | |
bar: 10, | |
multiplyByBar: function(...args) { | |
args.forEach(arg => console.log(arg * this.bar)); // arrow function does not change the context | |
} | |
}; | |
const qux = foo.multiplyByBar.bind(foo); | |
qux(5); // logs 50 |
OlderNewer