What is the difference between call and apply anyway? They both call the function?
The main difference between call and apply is that apply accepts an array of arguments.
Should you have a function like: function mixColor(color1, color2)
You can call it like mixColor.apply(undefined, colors)
mixColor.call(undefined, colors[0], colors[1])
While still allowing for mixColor(red, green) instead of mixColor([red, green])
There are also situations you might use it for variable length arguments, etc.
But that was not my real question, when the heck do you want to apply scope, why not pass in data???
Imagine this situation:
var person = {
name
dateOfBirth
function notifyBBQReady() ...
function BBQReady() ...
}
and you have a function which calls:
somelibrary.cookburgers().done(person.BBQReady)
when changeName is called from the promise, it will not have the "this" argument being person. If you use data like you suggested when I ask for "this.name" or call this.notifyBBQReady() it does not work as the "this" is not pointed at the person. If I passed "person" in as data I have to always use "person.name" and "person.notifyBBQReady()" and I can never call "person.BBQReady()" from within the object without using it differently from a regular method on the object.
This is how folks say to call the parent class method, etc.
In short, imagine this:
function dosomething(callback) {
....
callback()
}
quitButton { function successstatus() { this.$el.css('color', 'green'); } }
dosomething(quitButton .successstatus)
Will not work correctly but:
dosomething(function() { quitbutton.successstatus.call(quitbutton) }) will
and
dosomething(quitbutton.successstatus.bind(quitbutton)) also will
In shorter:
In javascript, any time you call a method on an object without the actual object as the context you get into trouble..but javascript being used as an OO language you often want a proper "this" instead of passing data around to every call you make.
Ah, it's all about using the "this" context. I avoid situations that involve using "this" entirely by using classless objects that are built by being passed through interfaces and built in layers, so that each object inherently knows what to do when invoked, despite possibly being completely seperate objects.
I appreciate this explanation though, it may come in handy one day if we are ever handed code with this style in place.
2
u/[deleted] Mar 11 '15
Forcing context on callbacks mostly