Skip to content

Instantly share code, notes, and snippets.

@etoxin
Last active May 10, 2016 00:24
Show Gist options
  • Save etoxin/36d42954c9b075fcdeb4a19b035990d7 to your computer and use it in GitHub Desktop.
Save etoxin/36d42954c9b075fcdeb4a19b035990d7 to your computer and use it in GitHub Desktop.
Call, Apply, Bind
/**
* Using apply and built-in functions
*
* Clever usage of apply allows you to use built-ins functions for some tasks that otherwise probably would have been written by looping over the array values. As an example here we are going to use Math.max/Math.min to find out the maximum/minimum value in an array.
*/
// min/max number in an array
var numbers = [5, 6, 2, 3, 7];
// using Math.min/Math.max apply
var max = Math.max.apply(null, numbers);
// This about equal to Math.max(numbers[0], ...)
// or Math.max(5, 6, ...)
var min = Math.min.apply(null, numbers);
var foo = {
x: 3
}
var bar = function(){
console.log(this.x);
}
bar(); // undefined
var boundFunc = bar.bind(foo);
boundFunc(); // 3
var myObj = {
specialFunction: function () {
},
anotherSpecialFunction: function () {
},
getAsyncData: function (cb) {
cb();
},
render: function () {
this.getAsyncData(function () {
this.specialFunction();
this.anotherSpecialFunction();
}.bind(this)); // we bind this to this function so the parent scope is available.
}
};
myObj.render();
var items = {
length: 2,
0: 'bob',
1: 'joe'
};
console.log(items.forEach); // => undefined
[].forEach.call(items, x => console.log(x)) // => bob => joe
var Cat = function(name) { this.name = name; }
var Dog = function(name) { this.name = name; }
Cat.prototype.sayHi = function() { console.log(`${this.name} meows loudly!`); };
Dog.prototype.sayHi = function() { console.log(`${this.name} barks excitedly!`); };
var whiskers = new Cat('whiskers');
var fluffybottom = new Dog('fluffy bottom');
whiskers.sayHi(); // => whiskers meows loudly!
fluffybottom.sayHi(); // => fluffy bottom barks excitedly!
Cat.prototype.sayHi.call(fluffybottom); // => fluffy bottom meows loudly!
whiskers.sayHi.call(fluffybottom); // => fluffy bottom meows loudly!
Dog.prototype.sayHi.call(whiskers); // => whiskers barks excitedly!
fluffybottom.sayHi.call(whiskers); // => whiskers barks excitedly!
/**
* Using call to invoke a function and specifying the context for 'this'
*
* In below example, when we will call greet the value of this will be bind to object i.
*/
function greet() {
var reply = [this.person, 'Is An Awesome', this.role].join(' ');
console.log(reply);
}
var i = {
person: 'Douglas Crockford', role: 'Javascript Developer'
};
greet.call(i); // Douglas Crockford Is An Awesome Javascript Developer
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment