I'm wondering why the variable is undefined if it's initialized within a callback function.
Pseudo code:
var name;
//callback function:
function(givenName) {
name = givenName;
}
alert(name) // undefined
The callback function is called from a different module that passes the givenName, and within the callback function name is defined as it should, but not outside the callback function. I'm curious to know how this works and how to get around it. Any articles or answers are more than welcome! thanks.
When this function is called from another context and you want to affect variables in the actual scope you will need to pass the context when calling this method.
Therefore you should use call or apply and pass the desired context as first parameter.
Hope this helps
Related
MY ISSUE
I've been learning the basics of AJAX from two different internet sources. In the multi-step process of sending an async HTTP request, there's one small inconsistency in how the .onload property is called on the XHR request object and then set to 1) an anonymous function or 2) a callback (??? that's what I think MDN says).
1ST APPROACH
the .onload property is called on the ourRequest object and this is set to an anonymous function:
ourRequest.onload = function() {
// the code goes here
}
2ND APPROACH
the .onload property is called on the asyncRequestObject object and this is set to the name of the function (a callback??):
function handleSuccess () {
// the code goes here
}
asyncRequestObject.onload = handleSuccess;
MY QUESTION(S)
What's the difference between how the 1st and the 2nd approach work?
And then, is there any reason to use the 1st approach over the 2nd approach?
A function declaration creates a (hoisted) variable in the current scope, that has the same name as the function, and whose value is a reference to that function.
A function expression simply evaluates as a reference to that function.
So the primary difference is that where you use handleSuccess, you can continue to reference the function for other purposes elsewhere.
What's the difference between how the 1st and the 2nd approach work?
The difference is that the first function is an anonymous function expression while the second is a function with a name. Both are event handlers for the "load" event of the XMLHttpRequest .
And then, is there any reason to use the 1st approach over the 2nd approach?
If you don't plan to reuse your handler somewhere else then you don't need to declare your function with a name.
It is no different than any other programming practice. Use a variable/constant when a value is called multiple times, otherwise use a literal.
I've been a Javascript tinkerer for quite some time and recently I have been trying to have a real good understanding of the code I write. I want to get really good at writing Javascript. One of the things that's confused me a little bit was the usage of callback functions. I've just avoided using callbacks up until now. Right now, I'd like to know if my understanding of how a basic callback works is accurate and also if my understanding of parameters and arguments is accurate and finally, what the purpose is of using the callback in this scenario. Is there a benefit to using the callback function I've created below? If not, when are callback functions most beneficial? I realize what I've written below is quite lengthy so for the TLDR people: Am I right in thinking It's as if I created the function "theCallback" within "myFunction"? If so, what is the benefit in the scenario below? Why not just call a function? why must the function being called be an argument in the "myFunction" function?
If the scenario below doesn't make it necessary for using a callback, when is it necessary and what are the benefits? Thanks.
Here's how I see the code below: I've created a factory function "myFunction" with two parameters "x" and "callback" and parameters are pretty much variables that will be stored with arguments when the function is called. I also created another factory function "theCallback" with two parameters "x" and "theValue". Now since these are factory functions, regardless of them being underneath a function call to "myFunction", they will be hoisted above the function call so there are no problems. Had I created a function expression with a variable, they would not be hoisted. So now my call to "myFunction" has two arguments that the parameters in it will be defined as, "3" and "theCallback". The "theCallback" argument is a function. This function has the two parameters "x" and "theValue". When "myFunction" is called, "x" is stored with the argument "3" and "callback" is stored with the function "theCallback" and then the code within "myFunction" is executed which is simply a variable declared and assigned a value of a string that contains the text "for the callback" and the callback variable (I'm viewing as a variable), which was a parameter that is now an argument which is "theCallback" function I created which also contains parameters itself, is called, and given arguments for it's code to execute. In this case, the code it will execute calls the built in alert function (or method of the window object?) and gives the alert function a string argument, followed by the
alert function called again with the argument of "x" which is stored with "3" and then again alert is called and given the argument of "theValue" which contains the string "for the callback". Now when "theCallback" function is passed as a second argument to "myFunction" and it's stored in "callback", It's as if I created the function "theCallback" within "myFunction" right? If so, what is the benefit in the scenario below? Why not just call a function, why must the function being called be an argument in the "myFunction" function?
If the scenario below doesn't make it necessary for using a callback, when is it necessary and what are the benefits?
myFunction(3, theCallback);
function myFunction(x, callback){
var value = 'for the callback';
callback(x, value);
}
function theCallback(x, theValue){
alert('this is the callback function');
alert(x);
alert(theValue);
}
Is there a benefit to using the callback function I've created below?
That's a little subjective. Using a callback is unnecessary there. Normally you would return data from one function and pass it to the other.
when are callback functions most beneficial?
When you need to deal with the data after an event has fired, instead of immediately. e.g. when a button is clicked or an HTTP response has fired.
myButton.addEventListener("click", myCallbackFunction);
I've created a factory function "myFunction"
No. That is just a function. Factory functions create class objects.
they will be hoisted
Function declarations (as opposed to function expressions) are hoisted. This isn't relevant to callbacks though. A callback is basically a function passed as an argument, it doesn't matter how it was created.
what are the benefits
The benefits are that you can have different things happen when the event fires depending on the circumstance.
Take the click event example above. Often you'll want clicking on different things to have different effects, not the one thing that addEventListener was hardcoded to make happen by the browser vendor.
Can somebody explain me what (this) means at the end of the following code:
var a=(function(_this){
return function() {
//do something
return smth;
};
})(this);
What is the sense of such coding?
Going forward, what does the following code do, when placed in .js file and invoked by html tag?
(function() {
Emitter=(function(){
function Emitter() {}
...
return Emitter;
})();
A=(function(_super){...})(Emitter);
}).call(this);
how to instantiate object A from outside the js file?
This is a self-executing function, which is used to save a reference to "this" through the function's closure. It is used to hold on to the reference to "this" at the function's first execution time.
You can also use Function.prototype.bind() to achieve a similar result of saving a reference to "this":
MDN - Bind
This whole structure is a means of saving the current value of this so that a function call later on can use it.
That could all be done also with .bind() like this which (if you understand what .bind() does might be easier to follow):
function myFunc(_this) {
// do something
}
var a = myFunc.bind(null, this);
Here are the various steps in what happens in the code you've shown:
this will have a value from the surrounding context when this code is originally executed (which you don't show). It is being passed into a self-executing function as an argument often referred to as an IIFE (immediately invoked function expression) which is just a function call that happens immediately inline as the code is initially run.
Within that function it is given an argument name of _this.
When that function executes, it returns another function. The body of that inner function also has access to _this.
When that inner function is returned, it is assigned to the variable a.
The upshot of all this is that one can call a() and the internals of that function, when it executes will be able to access _this which contains the value of the original this.
So, it's essentially a means of creating a function that when executed will have access to the original value of this even though the context will have changed when a() is later called. So, its essentially saving the value of this for a specific function to use later.
More detail would require more context about what is going on inside that internal function, what the this value was in the original context and how a() is used later.
This is one particular use of an IIFE. They have many other uses.
I have the following code;
function myFunction(promiseObject){
var that = this;
promiseObject
.done(function(){
//using that here
});
}
The above function gets called in multiple context and hence value for this changes in every call. The issue I am facing is that for many concurrent calls, the value for that gets overridden by another context which is also in process of completion.
I wanted to understand what could be the reason for this. Also wanted to understand that what is the concept behind scope of that variable defined in myFunction but used in the attached callback method.
Thanks in advance :)
-devsri
I hope that I understand your problem correctly. The concept behind the that variable being defined in myFunction and being accessible in the callback is lexical scoping at work. It's creating a closure (basically a reference to the execution environment of the function that the callback is defined in) for the callback to access.
The value of this inside of myFunction is going to depend on how you are calling myFunction.
If you want a myFunction to have a specific context you'll need to call it with that context like so:
var myContext = { foo: "bar" };
myFunction.call(myContext);
The value of this inside of myFunction will now be equal to myContext.
If you want your value of that to remain consistent between calls you'll need to make sure you call/apply myFunction with the correct context everywhere.
Alternatively you can use a function like underscore.js's _.bind:
myFunction = _.bind(myFunction, myContext);
myFunction will now always be bound to a specific context.
I have a function:
myObject.myFunction = function(callback){
callback();
}
and a callback
randomObject.callBack = function(){
console.log(this);
}
if I call randomObject.callBack() directly, I get the parent object in the console. However, if I call myObject.myFunction(randomObject.callBack), it logs a DOM Element.
How can I access the parent object?
Note
I do not know the name of the callbacks parent object ahead of runtime.
The context (i.e. this value) of an object is determined at the time the function is run, not at the time it is defined. Passing randomObject.callBack to another function does not send the context (the randomObject bit); it just sends the function.
Presumably the context is set when myFunction calls it. Since you aren't explicitly providing a context (e.g. with call or apply), the context will be the window object.
You can change this by explicitly saying what the context of the function should be before it is run. You can do this with the bind method:
myObject.myFunction(randomObject.callBack.bind(randomObject))
Now when you call callback inside myFunction, randomObject will be logged.
Note that bind is relatively new; not all browsers support it. The MDN page I linked to above has a bit of code that will make it work in all browsers.
This happens because when you invoke a function without an object, inside the function this will point to Window object.To avoid this we usually do like this
myObject.myFunction = function(callback){
callback();
}
randomObject.callBack = function(){
console.log(this);
}
function proxyCallback(){
randomObject.callBack();
}
myObject.myFunction(proxyCallback);
In javascript, this refers to the object context in which a function is called. This is not necessarily related to any object on which it has been defined.
You can think of it as though functions are not defined as members of objects, but called as members of objects.
There are four things that this might resolve to, depending on context.
A newly created object, if the function call was preceded by the new keyword.
The Object to the left of the dot when the function was called.
The Global Object (typically window), if neither of the above are provided.
The first argument provided to a call or apply function.
In your situation, something like this might be appropriate:
myObject.myFunction(function(){randomObject.callBack()});
This creates a closure so that within myFunction, callback is called as a member of randomObject.