I have a script with a similar structure to this
$(function(){
var someVariable;
function doSomething(){
//here
}
$('#something').click(function(){
//here
})
});
My question is;
From the doSomething function, and the click handler
how can I access the someVariable without passing it in?
Just use it. No need for this.
$(function(){
var someVariable = 3;
function doSomething(){
alert(someVariable);
}
});
You can use it without any special syntax. someVariable is available in closure scope of doSomething.
Read more on JavaScript closures
When ECMA- / Javascript methods are invoked (called), several things happen. To make a long story short, when a function is called a such called Activation object is created for that function. In that object you'll find things like arguments, local variables and function declarations and the arguments object. The "Context" of the invoked function has a [[Scope]] property. That is the place where all parent context's are stored when the function is invoked.
That concept (which I pretty much shrinked together here) is the basic thing to have closures. That means if you call doSomething() in your example, the function will copy the parent Context into it's [[Scope]], which includes someVariable. The anonymous function from your event listener does the same thing, both methods share the same scope.
Short answer: You can just use and access someVariable in all of methods.
Related
I'm a beginner to closures (and Javscript in general), and I can't find a satisfactory explanation as to what's going on in this code:
function myObject(){
this.myHello = "hello";
this.myMethod = do_stuff;
}
function do_stuff(){
var myThis = this;
$.get('http://example.com', function(){
alert(this.myHello);
alert(myThis.myHello);
});
}
var obj = new myObject;
obj.myMethod();
It will alert 'undefined' and then 'hello'. Obviously this should not be jQuery specific, but this is the simplest form of my original code I could come up with. The closure in do_stuff() has access to the variables in that scope, but apparently this rule does not apply to the this keyword.
Questions:
What happens to this when the closure is passed outside the scope of do_stuff() (in this case $.get())? Does myThis contain a copy of this or a reference to it? Is it generally not a good idea to use this in closures?
Any response much appreciated.
What happens to this when the closure is passed outside the scope of do_stuff() (in this case $.get())?
Each function has its own execution context, the this keyword retrieves the value of the current context.
The doStuff identifier and the obj.myMethod property refer to the same function object, but since you are invoking it as a property of an object (obj.myMethod();), the this value inside that function, will refer to obj.
When the Ajax request has succeeded, jQuery will invoke the second function (starting a new execution context), and it will use an object that contains the settings used for the request as the this value of that callback.
Does myThis contain a copy of this or a reference to it?
The myThis identifier will contain a reference to the object that is also referenced by the this value on the outer scope.
Is it generally not a good idea to use this in closures?
If you understand how the this value is handled implicitly, I don't see any problem...
Since you are using jQuery, you might want to check the jQuery.proxy method, is an utility method that can be used to preserve the context of a function, for example:
function myObject(){
this.myHello = "hello";
this.myMethod = do_stuff;
}
function do_stuff(){
$.get('http://example.com', jQuery.proxy(function(){
alert(this.myHello);
}, this)); // we are binding the outer this value as the this value inside
}
var obj = new myObject;
obj.myMethod();
See also:
‘this’ object can’t be accessed in private JavaScript functions without a hack?
$.get('http://example.com', function(){
alert(this.myHello); // this is scoped to the function
alert(myThis.myHello); // myThis is 'closed-in'; defined outside
});
note the anonymous function. this in that scope is the scope of the function. myThis is the this of the outer scope, where the myHello has been defined. Check it out in firebug.
'this' always refers to the current scope of execution, i believe. If you want to take the current scope and preserve it, you do what you did, which is assign this to another variable.
$.get('http://example.com', function(){
// inside jQuery ajax functions - this == the options used for the ajax call
});
What happens to this when the closure is passed outside the scope of do_stuff() (in this case $.get())?
Nothing "happens" to it, this is still this for that closure, the execution context of the functions called from the closure do not automatically inherit this.
Does myThis contain a copy of this or a reference to it?
All non-scalar assignments are references in JavaScript. So it is a reference to this, if you change properties on either, they change for both.
Is it generally not a good idea to use this in closures?
It is generally a good idea to use this in closures, but if you're going to be using closures inside that need to access the same this, its good practice to do exactly what you did: var someName = this; and then access using someName
I often see something like the following in JavaScript:
$("#sendButton").click(function() {
sendForm();
}
Why is it necessary to wrap the call to sendForm() inside a function? I would think that doing it like this would be more readable and less typing.
$("#sendButton").click(sendForm);
What are the advantages/disadvantages to each approach? thanks!
There's typically two cases where you'd want to use the former over the latter:
If you need to do any post-processing to the arguments before calling your function.
If you're calling a method on an object, the scope (this reference) will be different if you use the second form
For example:
MyClass = function(){
this.baz = 1;
};
MyClass.prototype.handle = function(){
console.log(this.baz);
};
var o = new MyClass();
$('#foo').click(o.handle);
$('#foo').click(function(){
o.handle();
});
Console output:
undefined
1
Probably one too many answers by now, but the difference between the two is the value of this, namely the scope, entering sendForm. (Also different will be the arguments.) Let me explain.
According to the JavaScript specification, calling a function like this: sendForm(); invokes the function with no context object. This is a JavaScript given.
However, when you pass a function as an argument, like this: $(...).click(sendForm), you simply pass a reference to the function for later invocation. You are not invoking that function just yet, but simply passing it around just like an object reference. You only invoke functions if the () follows them (with the exception of call and apply, discussed later). In any case, if and when someone eventually calls this function, that someone can choose what scope to call the function with.
In our case, that someone is jQuery. When you pass your function into $(...).click(), jQuery will later invoke the function and set the scope (this) to the HTML element target of the click event. You can try it: $(...).click(function() { alert(this); });, will get you a string representing a HTML element.
So if you give jQuery a reference to an anonymous function that says sendForm(), jQuery will set the scope when calling that function, and that function will then call sendForm without scope. In essence, it will clear the this. Try it: $(...).click(function() { (function() { alert(this); })(); });. Here, we have an anonymous function calling an anonymous function. We need the parentheses around the inner anonymous function so that the () applies to the function.
If instead you give jQuery a reference to the named function sendForm, jQuery will invoke this function directly and give it the scope that it promises to always give.
So the answer to your question becomes more obvious now: if you need this to point to the element target of the click when you start work in sendForm, use .click(sendForm). Otherwise, both work just as well. You probably don't need this, so skip the anonymous function.
For those curious, scope can be forced by using the JavaScript standard apply or call (see this for differences between the two). Scope is also assigned when using the dot operator, like in: obj.func, which asks of JavaScript to call a function with this pointing to obj. (So in theory you could force obj to be the scope when calling a function by doing something like: obj.foo = (reference to function); obj.foo(); delete obj.foo; but this is a pretty ugly way of using apply.
Function apply, used by jQuery to call your click handler with scope, can also force arguments on the function call, and in fact jQuery does pass arguments to its click handlers. Therefore, there is another difference between the two cases: arguments, not only scope, get lost when you call sendForm from an anonymous function and pass no parameters.
Here you are defining an anonymous event handler that could call multiple functions inline. It's dirty and tough to debug, but people do it because they are lazy and they can.
It would also work like your second example (how I define event handlers):
$("#sendButton").click(sendForm)
Something you get by defining your event handlers inline is the ability to pass event data to multiple functions and you get this scoped to the event object:
$("#sendButton").click(function(event) {
sendForm();
doSomethingElse(event);
andAnotherThing(event);
// say #sendButton is an image or has some data attributes
var myButtonSrc = $(this).attr("src");
var myData = $(this).data("someData");
});
If all you are doing is calling sendForm, then there isn't much difference, in the end, between the two examples you included.
$("#sendButton").click(function(event) {
if(event.someProperty) { /* ... */ }
else { sendForm({data: event.target, important: 'yes'}); }
}
However, in the above case, we could handle arguments passed to the callback from click(), but if the sendForm function is already equipped to handle this, then there's no reason why you wouldn't place sendForm as the callback argument if that is truly all you are doing.
function sendForm(event) {
// Do something meaningful here.
}
$("#sendButton").click(sendForm);
Note that it is up to you where you handle the differing layers of logic in your program; you may have encapsulated certain generic functionality in a sendForm function then have a sendFormCallback which you pass to these sorts of function which handle the interim business of event/callback processing before calling sendForm itself.
If you are working in a callback-heavy environment, it would be wise to separate significant functionality from the callback triggers themselves to avoid callback hell and promote maintainability and readability in your source code.
It's just to lock scope. When you wrap that sendForm() in the anonymous function that closes over the current scope. In other words, the this will be kept with it. If you just pass sendForm then any calls to this will come from the calling scope.
This is a good question for learning about scope in javascript, and questioning conventions.
Nope, that second example is perfectly valid.
99.9% of jQuery examples use the first notation, that doesn't mean you need to forget basic JavaScript syntax.
var main = {
doSomething: function(){
function firstOne(){}
function secondOne(){
$.ajax({
success: function(){
firstOne(); /* here I want the previous function */
}
});
}
}
}
How can I run the firstOne() function from the marked line? It's a noobish question perhaps, but I don't get the JS namespace (and I tried).
Is that kind of defining functions good from a JS good practices point of view?
What you do works. This passage of MDN explains why:
You can nest a function within a function. The nested (inner) function is private to its containing (outer) function. It also forms a closure.
...
Since a nested function is a closure, this means that a nested function can "inherit" the arguments and variables of its containing function. In other words, the inner function contains the scope of the outer function.
To summarize:
The inner function can be accessed only from statements in the outer function.
The inner function forms a closure: the inner function can use the arguments and variables of the outer function, while the outer function cannot use the arguments and variables of the inner function.
So this explains why you can call firstOne from within the Ajax callback.
Whether this is good design or not depends completely on what you are trying to achieve. If firstOne is something that you could reuse in several parts of your code, then it would certainly be a bad decision to define it as a nested function, where it can only be accessed in a local context. But if you had for example two Ajax calls within secondOne that both needed the same functionality in their callback, then it would be a good decision to wrap this in a local nested function. If you just need the behaviour once then it might be overkill (and extra typing) to declare it as a separate function.
Your code looks OK, and should run fine.
Unlike many other programming languages, Javascript has a scope lookup chain. If a function or variable is not found in the local scope, Javascript will look for it in the scope above that. If it's not found there either, it'll look for it further up in the chain, till it hits the head object (which in a browser would be the window object). If it's not found there, then it throws an error.
Since your firstOne() function is declared in the scope immediately above your AJAX object, Javascript should have no problem finding it for you. There's no need to manually reference the parent scope.
I now know this works:
function outerfunction(arg1, arg2, arg3) {
var others;
//Some code
innerFunction();
function innerFunction() {
//do some stuff
//I have access to the args and vars of the outerFunction also I can limit the scope of vars in the innerFunction..!
}
//Also
$.ajax({
success : secondInnerFunction;
});
function secondInnerFunction() {
// Has all the same benefits!
}
}
outerFunction();
So, I am not doing a 'new' on the outerFunction, but I am using it as an object! How correct is this, semantically?
There doesn't appear to be anything wrong with what you're doing. new is used to construct a new object from a function that is intended as a constructor function. Without new, no object is created; the function just executes and returns the result.
I assume you're confused about the closure, and how the functions and other variables belonging to the function scope are kept alive after the function exits. If that's the case, I suggest you take a look at the jibbering JavaScript FAQ.
You are not using the outer function as an object. You are using it to provide a closure. The border line is, admittedly, thin, but in this case, you are far away from objects, since you do not pass around any kind of handle to some more generic code invoking methods, all you do is limiting the scope of some variables to the code that needs to be able to see them.
JFTR, there is really no need to give the outer function a name. Just invoke it:
(function() { // just for variable scoping
var others;
...
})()
I do this sort of thing all the time. Yes - javascript blurs the boundary between objects and functions somewhat. Or perhaps, more correctly, a javascript function is just an object that is callable. You would only really use the 'new' prefix if you wanted to have multiple instances of the function. My only suggestion here is that its usually considered good practice to call a function after you've declared it (you are calling the innerFunction before it has been declared) - although that could be considered nit-picking.
This is a valid example.
Functions in JavaScript are first order objects. They can be passed as an argument, returned from a function or even set to a variable. Therefore they are called 'lambda'.
So when you are directly using this function (without new keyword) you are directly dealing with the function as an object. When u are using new keyword, you are dealing with an object instance of the function.
I'm a beginner to closures (and Javscript in general), and I can't find a satisfactory explanation as to what's going on in this code:
function myObject(){
this.myHello = "hello";
this.myMethod = do_stuff;
}
function do_stuff(){
var myThis = this;
$.get('http://example.com', function(){
alert(this.myHello);
alert(myThis.myHello);
});
}
var obj = new myObject;
obj.myMethod();
It will alert 'undefined' and then 'hello'. Obviously this should not be jQuery specific, but this is the simplest form of my original code I could come up with. The closure in do_stuff() has access to the variables in that scope, but apparently this rule does not apply to the this keyword.
Questions:
What happens to this when the closure is passed outside the scope of do_stuff() (in this case $.get())? Does myThis contain a copy of this or a reference to it? Is it generally not a good idea to use this in closures?
Any response much appreciated.
What happens to this when the closure is passed outside the scope of do_stuff() (in this case $.get())?
Each function has its own execution context, the this keyword retrieves the value of the current context.
The doStuff identifier and the obj.myMethod property refer to the same function object, but since you are invoking it as a property of an object (obj.myMethod();), the this value inside that function, will refer to obj.
When the Ajax request has succeeded, jQuery will invoke the second function (starting a new execution context), and it will use an object that contains the settings used for the request as the this value of that callback.
Does myThis contain a copy of this or a reference to it?
The myThis identifier will contain a reference to the object that is also referenced by the this value on the outer scope.
Is it generally not a good idea to use this in closures?
If you understand how the this value is handled implicitly, I don't see any problem...
Since you are using jQuery, you might want to check the jQuery.proxy method, is an utility method that can be used to preserve the context of a function, for example:
function myObject(){
this.myHello = "hello";
this.myMethod = do_stuff;
}
function do_stuff(){
$.get('http://example.com', jQuery.proxy(function(){
alert(this.myHello);
}, this)); // we are binding the outer this value as the this value inside
}
var obj = new myObject;
obj.myMethod();
See also:
‘this’ object can’t be accessed in private JavaScript functions without a hack?
$.get('http://example.com', function(){
alert(this.myHello); // this is scoped to the function
alert(myThis.myHello); // myThis is 'closed-in'; defined outside
});
note the anonymous function. this in that scope is the scope of the function. myThis is the this of the outer scope, where the myHello has been defined. Check it out in firebug.
'this' always refers to the current scope of execution, i believe. If you want to take the current scope and preserve it, you do what you did, which is assign this to another variable.
$.get('http://example.com', function(){
// inside jQuery ajax functions - this == the options used for the ajax call
});
What happens to this when the closure is passed outside the scope of do_stuff() (in this case $.get())?
Nothing "happens" to it, this is still this for that closure, the execution context of the functions called from the closure do not automatically inherit this.
Does myThis contain a copy of this or a reference to it?
All non-scalar assignments are references in JavaScript. So it is a reference to this, if you change properties on either, they change for both.
Is it generally not a good idea to use this in closures?
It is generally a good idea to use this in closures, but if you're going to be using closures inside that need to access the same this, its good practice to do exactly what you did: var someName = this; and then access using someName