Skip to content

Instantly share code, notes, and snippets.

@koozdra
Last active October 20, 2015 18:27
Show Gist options
  • Save koozdra/3640cf39b69f322d6994 to your computer and use it in GitHub Desktop.
Save koozdra/3640cf39b69f322d6994 to your computer and use it in GitHub Desktop.
Apply, Call, This and That
function add(a, b, c) {
return a + b + c;
}
console.log( add.apply(null, [1, 2, 3]) );
// 6
console.log( add.call(null, 2, 3, 4) );
// 9
var myObject = {
x: 81,
whatIsThisX: function (y){
return [this.x, y];
}
}
console.log( 'original this: ', myObject.whatIsThisX(64) );
// [81, 64]
console.log( 'replaced this: ', myObject.whatIsThisX.bind({x:9})(4) );
// [9, 4]
console.log( 'call: ', myObject.whatIsThisX.call({x:5}, 45) );
// [5, 45]
console.log( 'bind: ', myObject.whatIsThisX.bind({x:10}, 12)() );
// [10, 12]
console.log( 'apply: ', myObject.whatIsThisX.apply({x:6}, [39]) );
// [6, 39]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment