javascript class member is undefined in local function [duplicate] - javascript

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

Related

Javascript hide the context

What's the best way for a method to call another method and pass the arguments in not-by-reference fashion?
i.e.
function main() {
let context = {};
// Pass context to someOtherFunction
// Such that console.log(context) in this function does not show `{whatever: true}`
}
function someOtherFunc(context) {
context.whatever = true;
}
I realize I can clone the context and pass that. But I was wondering if there was another way to do this, maybe using anonymous function wrap?
Okay, let's break this down a bit
const context = {x: true};
Above, you create an object (named context) in the global scope.
function(x) {
"use strict";
x.y = true;
}
You create an anonymous function that takes a reference to an object, and adds a new property y to that object
(/*...*/)(context);
You wrapped the above function into an IIFE so it immediately executes. For the parameter, you supplied a reference to the global context object, which is referenced by x inside the IIFE.
Objects are passed around by reference. Passing context in to the function doesn't create a new object x that is a copy of the context, it creates a new reference x that references the same object that context references.
If you need to actually copy the provided object into a new object, you need to do that yourself. As mentioned above, one mechanism is to stringify the object into JSON and then parse the JSON back to a new object. There are others depending on what you need to accomplish.
This isn't even a scope or context question at all - it's passing a reference to an object in to a function. Even if your IIFE had no way whatsoever of directly accessing the context variable, once you pass a reference to that object as an input to the function, the function has the reference and can do what it likes to it.
You also seem to misunderstand about how IIFEs hide data. You hide things inside the IIFE from things outside, not vice versa. Even then, it won't prevent you from passing a reference outside of the IIFE. Here's an example:
function changeName(animal) {
"use strict"
//myDog.name = "Rex"; // Error - myDog isn't a valid reference in this scope
//myCat.name = "Rex"; // Error - myCat isn't a valid reference in this scope either
animal.name = "Rex"; // Perfectly legal
}
(function () {
var myDog = {name: "Rover"};
var myCat = {name: "Kitty"};
console.log(myDog);
console.log(myCat);
changeName(myDog); // Even though changeName couldn't directly access myDog, if we give it a reference, it can do what it likes with it.
console.log(myDog);
})()
In this case, changeName has no access to myDog or myCat which are purely contained within the closure formed by the IIFE. However, the code that exists within that IIFE is able to pass a reference to myDog to changeName and allow it to change the name of the dog, even though changeName still couldn't access the object using the myDog variable.
This is because you are not technically redefining x, but adding properties to it.
I didn't really understood where your doubts came from so this is (to the best of my knowledge) an explanation of what your code is doing.
I'll try to translate the code to human-english.
Define the variable context in the "global scope". (It can be read from anywhere)
It cannot be redefined because its a constant.
Afterwards, define an anonymous self-invoking function (which "starts" a new "local scope" above the global scope so it has access to everything the global scope had access to)
This self invoking function grabs parameter x and adds the property y with a value of true to x and calls itself with the variable context
Read the value of context.
Please read:
JavaScript Scope
JavaScript Function Definitions (Self-Invoking Functions)

Understanding Javascript scope with "var that = this" [duplicate]

This question already has answers here:
In Javascript, why is the "this" operator inconsistent?
(8 answers)
Closed 9 years ago.
Say I have the following property method in an object:
onReady: function FlashUpload_onReady()
{
Alfresco.util.Ajax.jsonGet({
url: Alfresco.constants.PROXY_URI + "org/app/classification",
successCallback: {
fn: function (o) {
var classButtonMenu = [],
menuLabel, that = this;
var selectButtonClick = function (p_sType, p_aArgs, p_oItem) {
var sText = p_oItem.cfg.getProperty("text");
that.classificationSelectButton.set("label", sText);
};
for (var i in o.json.items) {
classButtonMenu.push({
text: o.json.items[i].classification,
value: o.json.items[i].filename,
onClick: {fn: selectButtonClick}
});
}
this.classificationSelectButton = new YAHOO.widget.Button({
id: this.id + "-appClassification",
type: "menu",
label: classButtonMenu[0].text,
name: "appClassification",
menu: classButtonMenu,
container: this.id + "-appClassificationSection-div"
});
},
scope: this
},
failureMessage: "Failed to retrieve classifications!"
});
It took me some guess work to figure out that in the selectButtonClick function that I needed to reference that instead of this in order to gain access to this.classificationSelectButton (otherwise it comes up undefined), but I'm uncertain as to why I can't use this. My best guess is that any properties in the overall object that gets referenced within new YAHOO.widget.Button somehow looses scope once the constructor function is called.
Could someone please explain why it is that I have to reference classificationSelectButton with var that = this instead of just calling `this.classificationSelectButton'?
The most important thing to understand is that a function object does not have a fixed this value -- the value of this changes depending on how the function is called. We say that a function is invoked with some a particular this value -- the this value is determined at invocation time, not definition time.
If the function is called as a "raw" function (e.g., just do someFunc()), this will be the global object (window in a browser) (or undefined if the function runs in strict mode).
If it is called as a method on an object, this will be the calling object.
If you call a function with call or apply, this is specified as the first argument to call or apply.
If it is called as an event listener (as it is here), this will be the element that is the target of the event.
If it is called as a constructor with new, this will be a newly-created object whose prototype is set to the prototype property of the constructor function.
If the function is the result of a bind operation, the function will always and forever have this set to the first argument of the bind call that produced it. (This is the single exception to the "functions don't have a fixed this" rule -- functions produced by bind actually do have an immutable this.)
Using var that = this; is a way to store the this value at function definition time (rather than function execution time, when this could be anything, depending on how the function was invoked). The solution here is to store the outer value of this in a variable (traditionally called that or self) which is included in the scope of the newly-defined function, because newly-defined functions have access to variables defined in their outer scope.
Because this changes its value based on the context it's run in.
Inside your selectButtonClick function the this will refer to that function's context, not the outer context. So you need to give this a different name in the outer context which it can be referred to by inside the selectButtonClick function.
There's lexical scope: variables declared in functions and arguments passed to functions are visible only inside the function (as well as in its inner functions).
var x = 1; // `1` is now known as `x`
var that = this; // the current meaning of `this` is captured in `that`
The rules of lexical scope are quite intuitive. You assign variables explicitly.
Then there's dynamic scope: this. It's a magical thing that changes it's meaning depending on how you call a function. It's also called context. There are several ways to assign a meaning to it.
Consider a function:
function print() { console.log(this); }
Firstly, the default context is undefined in strict mode and the global object in normal mode:
print(); // Window
Secondly, you can make it a method and call it with a reference to an object followed by a dot followed by a reference to the function:
var obj = {};
obj.printMethod = print;
obj.printMethod(); // Object
Note, that if you call the method without the dot, the context will fall back to the default one:
var printMethod = obj.printMethod;
printMethod(); // Window
Lastly, there is a way to assign a context is by using either call/apply or bind:
print.call(obj, 1, 2); // Object
print.apply(obj, [ 1, 2 ]); // Object
var boundPrint = print.bind(obj);
boundPrint(); // Object
To better understand context, you might want to experiment with such simple examples. John Resig has very nice interactive slides on context in JavaScript, where you can learn and test yourself.
Storing it in a variable lets you access it in other scopes where this may refer to something else.
See https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Operators/this, http://www.quirksmode.org/js/this.html and What is the scope of variables in JavaScript? for more information about the this keyword.
The this reference doesn't work when a method of a class is called from a DOM event. When a method of an object is used as an event handler for onclick, for example, the this pointer points to the DOM node where the event happened. So you have to create a private backup of this in the object.
this is a keyword in javascript, not a default variable defined within every function, hence, as Gareth said, this will refer to the context in which the function is invoked, or the global object if there's no context.

But var it is not for local variable?

This is my code :
var markers={};
example();
function example() {
var myFunct = function () {
alert("hello");
};
markers["myIndex"] = myFunct;
}
markers["myIndex"]();
as you can see, myFunct is "var" (so, when example() finish, it will be destroyed, because it is local). But in fact, accessing to markers["myIndex"](), the function is referenced, and I can access to it. Why?
This doesn't work the way you expect it to. In other words, when example() finishes, myFunct will not be destroyed because there is still a reference to that function in a variable from an outer scope, markers.
The only way it would be 'destroyed' is if nothing else referenced it at the end of example() or if only variables with equal or lower scope referenced it, provided those variables also followed the same rules and were not referenced from outer variables.
In JavaScript, functions are objects just like other objects. When you do this:
var myFunct = function () {
alert("hello");
};
...you're creating a function and assigning a reference to that function to the variable myFunct. Then when you do this:
markers["myIndex"] = myFunct;
...you're assigning another reference to that function to markers["myIndex"]. So regardless of anything else that might happen to the myFunct variable, because markers["myIndex"] still has a reference to the function, the function is kept in memory.
But separately, there's a more subtle misunderstanding in your question as well: You've said:
myFunct is "var" (so, when example() finish, it will be destroyed, because it is local)
That's not true in JavaScript. In JavaScript, local variables are actually properties of a hidden object, called (deep breath) the variable binding object of the execution context (let's just call it the "variable object"). This object is associated with the particular call to example: It's created when the call to example is executed. Now, in the normal course of things, when example returns, if nothing has any outstanding reference to the variable object, then you're quite correct that it is eligible for garbage collection. But in your case, something does have a reference to the variable object: The function you created. When you create a function, it receives an implicit reference to the variable object for the context in which it was created, and it keeps that reference for as long as the function exists. So even though the function you're creating doesn't refer to anything in the variable object for the call to example, it has that reference to it nevertheless, and the variable object cannot be reclaimed until or unless nothing has a reference to the function anymore. This is how closures work. The foregoing text notwithstanding, closures are not complicated, they're really, really simple when you understand how they work.
(I'll just note here that some JavaScript engines introspect the code sufficiently that they can reclaim variable objects even when there are outstanding closures that refer to them. Specifically, if the closures [functions] don't actually use any of the variable object's properties, and they don't use eval, then the engine may be able to release the variable object. Chrome's V8 engine does this, for instance. But that's a runtime optimization; the concept is as described above.)
Because you have assigned it to the global variable markers from within your example function.
you're assigning a reference to the function object to a higher scope (if not global scope) object. So while myFunct would be garbage collected, the function is not, since there is another reference to it in the markers object.
A reference from var myFunct to the actual function object (function() { ... }) will indeed be destroyed. But the object itself will not, as it is referenced by a markers field. Once there are no live references to the function object from live JS objects, this function object will be eligible for garbage collection.

Is it good to write javascript functions inside functions and not use 'new' on the main function?

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.

Why doesn't this closure have access to the 'this' keyword? - jQuery

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

Categories

Resources