This question already has answers here:
What does "this" mean in jQuery? [duplicate]
(6 answers)
Closed 7 years ago.
Reviewing some legacy code and saw it. The function body was done in pure Javascript without using any 3rd party library.
Could anyone shed a light on the use of "this" in (function() { })(this)?
Full codes:
(function() {
var root = this;
var SOMEVAR;
SOMEVAR = root.SOMEVAR = {};
SOMEVAR.windowOffset = 0;
SOMEVAR.defaultBase = 195;
SOMEVAR.resizeIFrame = function(){
// some codes
};
SOMEVAR.resetIFrameSize = function(height) {
// some codes
}
window.SOMEVAR = SOMEVAR;
})(this);
I actually read all "this" related usages before I asked the question. I just couldn't find this usage fits in those I read. And somehow, I don't think the "this" here is not even necessary because all the codes want is to create the "SOMEVAR" and bind it to "window". Am I correct?
Thanks
This is a somewhat weird example of an Immediately-Invoked Function Expression (IIFE). The first part:
(function(){})
simply defines a function (the outer parentheses are unnecessary). This function is then called, passing this as an argument. Usually one would actually declare a parameter and then do something to the parameter inside the function:
(function(context) {
// do something to or with context
})(this);
What object is actually referenced by this depends on where this code is executing and whether strict mode is in effect. See the docs for this for more information.
You're defining an anonymous function and then immediately invoking it with the this parameter.
If you're just looking to understand the meaning of this, then refer to this other question.
Ah, what is this. The oldest question in the javascript book. Generally speaking, this refers to the context that the current code is being executed in. If you have "top level" code being run straight in a script tag, it refers to window. In a click event? The current element. In a constructor? The object that will be constructed. You can even make it whatever you want with call and apply.
If you see this construct:
(function(ns) { })(this);
not inside other function then this is a reference of default namespace of script execution. In browsers that default namespace has quite strange name window therefore the following will output true:
(function(ns) {
console.log( ns === window );
})(this);
Such ns (namespace) variable is useful when you need for example check variable existence in namespace. This, for example:
alert(foo);
will rise an error "undefined variable foo", but this:
(function(ns) {
alert(ns.foo);
})(this);
will show alert with the word "undefined".
Another usage is in modules that can work as inside browser as in node.js and the like. Node.js has no notion of window so that construct above is the only reliable way to get reference to default namespace/scope object.
Related
This question already has answers here:
Is 'window' always on top of the scope chain in javascript?
(5 answers)
Closed 8 years ago.
As I understand from my practice (in the Google Chrome Console), we can change the definition of predefined functions. Let me explain through code:
function alert(){
return 2+2;
}
and I am calling alert("hi"), it is returning 4, it's Ok, as we have defined.
But, even when I call window.alert("hi"), it is returning 4, which is unexpected (for me).
Here I just created a new function, I have not mentioned any object name or Prototype property, but still it is overriding the window object properties itself.
My doubt is, if we change the definition of the function, will it override the definitions of a function with the same name in all the objects??
Let's say I have two objects objA and objB, both are having a function named strange(). Now I am defining a function strange() in the outside of both the objects. Then, whether it will override the definition of strange() in both objA nad objB? If so, why?
If so, how to prevent this? means how to prevent the overriding in all the objects?
Thanks in advance...!!!!
No - by declaring function alert() you are redefining window.alert() function because the default scope is window
var newObj = {
alert: function() {
return "this is a functino on my newObj object";
}
};
function alert() {
return 2 + 2;
}
console.log(alert());
console.log(window.alert());
console.log(newObj.alert());
The reason defining alert overrides the window property is because you declared it in the global context; anything declared in the global context will, by default, attach itself to window. To not override the window object, declare your function inside another function (or use a different name):
// This creates an anonymous function
(function() {
// Since alert is defined in this function (not the global scope)
// It won't override window.alert
function alert() { /* Do something */ }
})();
// You can no longer access the old alert here, so alert will refer to window.alert
In addition, if you add alert to a specific object, it will not change the alert of any other object, unless you use a with statement (considered bad practice).
var myNamespace = {
alert: function() { /* Custom alert */ }
}
// Will not change myNamespace.alert
function alert() {}
No I don't think so - with the alert function, the "window." prefix is assumed so really window.alert() and alert() are the same thing. I guess it's a short-cut to stop you havign to type window. all the time.
Regarding your other example, objA.strange() isn't related to objB.strange() (assuming objA and objB are in fact different objects).
the function strange() outside of both these objects is actually in window.strange() (it's implied) so again it's a different function under a different object.
You can, I gather, use prototype to redefine native JS functions, but this is normally undesirable.
If you define a variable or function in the default scope in javascript (creating a function directly inside a <script> tag for instance), it is considered part of the window object (if javascript is executed in a browser environment).
So, when you call (the default) alert, you arev actually calling window.alert.
Let's say I have two objects objA and objB, both are having a function
named strange(). Now I am defining a function strange() in the outside
of both the objects. Then, whether it will override the definition of
strange() in both objA nad objB
A definition of strange outside both the object scope (closure) will not impact the definition of the function (method) in the object. But if you define strange within the object again, the latter one will shadow the previous one.
It boils down to the scope of the function and the closure withing which the function (or variable) is defined.
See also
Functions and function scope from MDN. This will answer most of your questions
Closure from John Resig's Learning Advanced Javascript
This question already has answers here:
this in a global scope
(4 answers)
Closed 9 years ago.
I have read a couple of articles on the web explaining this in Javascript. While the articles
have helped a lot, the behavior shown below is still unclear to me.
Here it says:
In the global execution context (outside of any function), this
refers to the global object, whether in strict mode or not.
If so, can someone please explain the behavior (noted in the comments) when the following code is
run with node.
console.log(this); // Returns an empty object: {}.
// Why does this line not return the global object.
var somefunc = function(name) {
console.log(this);
}
somefunc(); // Returns the the global object. I think I understand this. The function is
// invoked in a global context.
somefunc.call(this); // Again returns the empty object. Why?
Thanks for your help.
EDIT (as requested by below by the moderators)
*How is this question and the chosen answer different from the one linked above*
I think both the question and certainly the answer here is clearer than the one that is considered a duplicate. The answer here clarifies what node is doing by giving example code, which is more helpful.
The first and the third showing of this should be identical in any case: in first case you just output the current value of this, and in the third you pass, again, the current value of this into somefunc (as a context argument).
But in the second, it's different: you call this function without assigning it any specific context, so this inside it points to a global object.
Why do you get an empty object as a result? One explanation is that your code is actually wrapped into some generic closure, like this:
var sandbox = {};
(function() {
console.log(this); // 1
var somefunc = function(name) {
console.log(this);
}
somefunc(); // 2
somefunc.call(this); // 3
}).call(sandbox);
As this function is called in sandbox context, both 1 and 3 point to sandbox - that is an empty object. 2 is different: you don't supply any context to this function call, that's why inside the function (when it's called that way) this points to global.
And that's exactly what happens when you try to access this in a global context of Node module. I'll quote an explanation from this discussion:
Node's modules are wrapped in a closure, which is evaluated in the
this-context of the exports object. So, if you do var a = 3, then
it won't be added to this, global, or exports. But, if you do this.a
= 3 then it'll be added to this and exports.
See: https://gist.github.com/788414
Note that it's quite different from using the code as it is within a browser. It's not wrapped in any closure, so all the calls - 1, 2 and 3 - are referring to the global object. And that's, as you know, window.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
JavaScript: var functionName = function() {} vs function functionName() {}
What is the difference between a function expression vs declaration in Javascript?
What is the right way to declare Javascript Function?
From codeacademy.com i got this way:
var someFunction = function(paramA, paramB){
// do some function here
}
But because my basic of programming is PHP, i prefer declare function with this way:
function someFunction(paramA, paramB){
// do some function
}
What I'm concern is which one is recommended way to declare function, I'm afraid if my preferred way have some consequences, but i love that way so much because it make my NetBeans Code Navigator can read all of my functions.
Both are acceptable. Indeed, you can also do:
foo = function bar() {
console.log(arguments.callee.name);
};
If you then call foo(), you'll see "bar" in the console.
The first method creates an anonymous function and assigns it to a variable.
The second method creates a named function and places it within the current scope.
The third method creates a named function and assigns it to a variable. However, this time, the name only exists within the scope of that function.
Declaring a function with a name (function name () {}) has the advantage that you can then call the function more easily from inside itself, as may be necessary for implementing a recursive algorithm. If you don't, you have to use arguments.callee.name in order to call a function within itself, but that is warned against in MDN.
All of that is a long-winded way of saying that either is acceptable and, if in doubt, you can't go much wrong with using named functions.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What does this “(function(){});”, a function inside brackets, mean in javascript?
javascript anonymous function
(function())()
this is used in many js library like jquery,YUi
Thats called Module Pattern. The idea is to have an encapsulated module, that cannot conflict with any other modules you or someone else has created. You can create public and private methods within that module.
See: Js Pattern
I'm not sure what (function())() means, but I'll work on the assumption that you meant (function() { … })(). It is roughly the same as:
f = function() { … }; // Define a function.
f(); // Call it.
The only difference is that it does so without requiring a variable.
It is an anonymous self executing function. It is anonymous, because it is not named, and self executing, so it runs (there would be no other way to run an un-named function).
It is particularly useful to enclose a discreet module of code, because it acts as a closure preventing variables leaking into the global namespace.
You're immediately calling an anonymus function with a specific parameter.
An example:
(function(name){ alert(name); })('peter') This alerts "peter".
In the case of jQuery you might pass jQuery as a parameter and use $ in your function. So you can still use jQuery in noConflict-mode but use the handy $:
jQuery.noConflict() (function($){ var obj = $('<div/>', { id: 'someId' }); })(jQuery)
It simply executes the code wrapped in parentheses right away (the first block returns a function, the second pair of parens executes it).
Take for instance these two snippets:
function foo() {
print 'foo';
}
(function() {
print 'foo';
})();
The first won't do anything until you call foo(); whereas the second will print 'foo' right away.
This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Javascript: var functionName = function() {} vs function functionName() {}
Way 1:
function fancy_function(){
// Fancy stuff happening here
}
Way 2:
var fancy_function = function(){
// Fancy stuff happening here, too.
}
I use the former when I'm just defining a "normal" function that I'm gonna use one or several times and the latter when I'm passing it a callback for another function or so, but it looks to work fine in the both ways.
Is it really a difference in some way?
There is no difference to the function itself, but the latter gives you more flexibility as you have a reference to the function and it is different with regard to how it behaves if overwritten.
This allows you to achieve behaviours with the latter that you cannot achieve with the former; such as the following trick to "override" an existing function and then call the "base":
var myOriginalFunction = function() {
window.alert("original");
}
var original = myOriginalFunction;
var myOriginalFunction = function() {
window.alert("overridden");
original();
}
myOriginalFunction();
This gives you an alert "overridden", followed by an alert "original".
However, if you attempt this with the former notation, you'll find you get stuck in a never ending loop of alert "overidden".
In the first sample you are defining a named function -- that function will always be known by that name. Defining a different function with the same name will be an error (unless you assign to the window property directly). In the second sample, you are defining an anonymous function and assigning it as the value of a variable. You can change the value of the variable to any other function later as desired; losing, of course, any reference to the anonymous function in the process unless you've stored it elsewhere. So, you're not really doing the same thing in both cases, though you can treat it that way if you wish -- and make sure to define the function before it's used in the second case, though that's more a function of variables than functions per se.
function definition
function literal assignment
only difference is you can access the former instantly in certain cases whereas you have to wait for the assignment on the latter.
Don't run this in firebug console/interpreter to test it, rather test on a real html page.
say('spotted');
function say(msg){ alert(msg) }
The above will work, but if you defined a function literal with var say = function(){} below, it would complain that it isn't defined yet.
You can use either depending on the situation, both become the methods of the window object. The later is known as anonymous function.
As far as the function is concerned, they will behave identically.
See here for more details: http://javascript.about.com/library/blfunc.htm
Functions defined with the Function(){} style are available throughout the program, without having to be defined earlier in the code than where they are called. It's called 'hoisting', I believe.
so this works
cow('spotted');
function cow(color){ return 'cow is '+color; }
but this throws an error
cow('spotted');//cow isn't defined yet!
var cow=function(color){ return 'cow is '+color; }