Skip to content

Instantly share code, notes, and snippets.

@mikepenzin
Created February 28, 2017 15:04
Show Gist options
  • Save mikepenzin/595e33a9f90f52c9658b8ef8b56d8905 to your computer and use it in GitHub Desktop.
Save mikepenzin/595e33a9f90f52c9658b8ef8b56d8905 to your computer and use it in GitHub Desktop.
Call / Apply / Bind functions examples.
// Generally speaking: stabilizing the "this" keyword.
var person = {hi: "Hello"};
function showFullName(pep) {
console.log (this.hi);
}
showFullName.call(person);
// Output: Hello
// ------------
var mike = {
checkThis: function() {
function checkOther(){
console.log(this);
}
checkOther.call(this)
}
}
mike.checkThis();
// Output: mike Object
// ------------
function a(b,c,d){
console.log(this);
console.log(b);
console.log(c);
console.log(d);
}
a.call(1,2,3,4);
// this = 1
a.apply(1, [2,3,4]);
// this = 1
// apply function need to passing in an array of parameters - this only difference with call function.
// So, both methods "a.call(1,2,3,4);" and "a.apply(1, [2,3,4]);" are equivalent with same output.
a(1,2,3,4);
// this = window object
// ------------
function sum(){
var total = 0;
for (var i = 0; i <arguments.length; i++){
total += arguments[i];
}
return total;
}
var x = sum.call(null, 1,2,3);
// Output: 6
var thing = [1,2,3];
var x = sum.apply(null, thing);
// Output: 6
// ------------
"use strict";
var a = function(){
console.log(this);
}.bind(2);
a();
// Output: undefined
// Inside bind fucntion, we actually defining "this" keyword paraemter
"use strict";
var a = function(){
console.log(this);
}.bind(2);
a();
// Output: 2
// Just another way of binding
"use strict";
function a(){
console.log(this);
};
var f = a.bind(2);
f();
// Output: 2
var mike = {
checkThis: function() {
var checkOther = function(){
console.log(this);
}.bind(this);
checkOther();
}
}
mike.checkThis();
// Output: Object{} - // name of the Object is checkThis as expected
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment