How are both of these referring to the same variable? - javascript

I have a very confusing situation...
(function sayStuff(){
this.word = "hello2";
(function (){
console.log(this.word);
}())
}())
var myObject = {
word: "bar",
func: function() {
(function() {
console.log(this.word);
}());
}
};
myObject.func();
Outputs
hello2
hello2
How is this happening? How can the closure on the 'func' of myObject actually see the variable that is referenced in sayStuff()? I thought IIFE were meant to protect internals from Global scope?

In both cases, this is window, the global default context replacing the one you don't provide when you call the internal function expressions.
If you want to keep the context, don't use IIFE internally or call them with the context :
(function sayStuff(){
this.word = "hello2"; // still this is window, use var if you don't want that
(function() {
console.log(this.word); // window.word
}).call(this); // well, this is window...
}())
var myObject = {
word: "bar",
func: function() {
(function() {
console.log(this.word); // myObject.word
}).call(this);
}
};
myObject.func();

IIFE only hide locally scoped variables (i.e. those created with the var keyword).
All your functions that touch this.word are invoked in the global context (i.e. not as methods of an object, not with the new keyword and not with apply, call or bind), so this is window in each case. You are dealing with global variables.
If you wanted a private variable you would do something more like this:
(function (){
var word = "hello2";
(function (){
console.log(word);
}())
}())

Related

JavaScript Function Hoisting in my Object

I have created an object and am attaching a bunch of functions to the object. I am concerned about how the ordering of the functions effects when I can call my functions. In my example below, I must define my functions first before I can use them. My problem with this is that I cannot call init() immediately until I have defined it. Init() will contain a bunch of other functions that it will need to call, which will have to be placed above init(). So in the end, init() will have to be the very last function defined in my object. I believe this is related to Hoisting.
My question is if there is a way for me to call a function before defining it? Is there some sort of way to create a 'placeholder' function like in C?
https://jsfiddle.net/13hdbysh/1/
(function() {
foo = window.foo || {};
//this will not error
foo.helloWorld = function() {
console.log('helloWorld()');
};
foo.helloWorld();
//this will error
foo.init();
foo.init = function() {
console.log('init()');
};
})();
What you're asking deals with how objects store member data. This can be seen in a weird light because of prototypal inheritance. Javascript by default will parse naked functions before they execute.
Example:
(function() {
init();
function init()
{
console.log("Init");
}
)};
This gets muddied when storing behavior as a member to an object. Because prototypal inheritances dynamic functionality you need to declare your members before accessing them. This is Javascript's main difference from traditional OOP languages.
You mentioned, "is there a way to create a 'placeholder' function like in C." You can, but not in the same way. You can assign it to a naked function and assign that to your object. Look in my example, the hello function.
Alternatively you can store the behavior on the prototype of your object and override it when necessary.
Example:
function hello()
{
console.log("Hello my name is "+this.name);
}
(function() {
var something = function(name) {
this.name = name;
};
something.prototype.initTwo = function() {
console.log("My Name is: "+this.name);
};
var thingOne = new something("Thing One");
thingOne.init = "SomeThing";
var thingTwo = new something("Thing Two");
thingTwo.init = function() {
console.log(this.name);
};
thingTwo.initTwo = function() {
console.log("SomethingTwo is Named: "+this.name);
};
thingTwo.hello = hello;
console.log(thingOne.init);
thingTwo.init();
thingOne.initTwo();
thingTwo.initTwo();
thingTwo.hello();
}) ();
Demo: Fiddle
Documentation on objects in javascript.
Try using similar IIFE pattern
(function() {
foo = window.foo || {};
//this will not error
foo.helloWorld = function() {
console.log('helloWorld()');
};
foo.helloWorld();
//this will error
// foo.init();
foo.init = (function _foo() {
console.log('init()');
this.init = _foo;
return this.init
}).call(foo);
foo.init()
})();
jsfiddle https://jsfiddle.net/13hdbysh/2/
I am not sure why would you wanna call it before it is defined but here is how to do it:
foo = window.foo || { init: function() { } };
How about declaring it as a local variable first.
(function() {
foo = window.foo || {};
//this will not error
foo.helloWorld = function() {
console.log('helloWorld()');
};
foo.helloWorld();
var initFunction = function() {
console.log('init()');
};
//this will no longer error
initFunction();
foo.init = initFunction;
})();
Init() will contain a bunch of other functions that it will need to call, which will have to be placed above init().
You are operating under a misapprehension.
A function must be defined before you call it, not before you define another function which will call it later.
Just define all your functions and then start calling them.
(function() {
foo = window.foo || {};
foo.helloWorld = function() {
console.log('helloWorld()');
};
foo.init = function() {
console.log('init()');
};
foo.init();
foo.helloWorld();
})();
As far as hoisting is concerned, function declarations (you only have function expressions) are hoisted, but they create locally scoped variables, not object properties. You would have to assign them to object properties before you could call them as such, and that assignment wouldn't be hoisted.
It's throwing an error because you're calling the method init() before it's declared.
This way will works
foo.init = function() {
console.log('init()');
};
foo.init();
Since foo is an object, you can put those functions into an object so that will be assigned to foo once window.foo is null
(function() {
foo = window.foo || {
helloWorld: function() {
console.log('helloWorld()');
},
init: function() {
console.log('init()');
}
};
//this will not error
foo.helloWorld();
foo.init()
})();

Specify global context in JavaScript

In JavaScript, is it possible to specify the global context which will be used if a local variable isn't defined?
Example:
(function foo() {
console.log(bar);
})();
It will actually print window.bar.
Can I somehow change the global context? Something like this:
var myGlobalContext = { bar: "foo" };
(function foo() {
console.log(bar);
}).applyWithGlobal(myGlobalContext);
It should print myGlobalContext.bar.
Or attach this to be the global context?
I hope the example is clear enough.
The closest thing you can do is mask the global variables using a with statement.
var myGlobalContext = {bar: "foo"};
with(myGlobalContext)
{
console.log(bar);
}
This is not the same as changing the global context, because other globals that aren't found in myGlobalContext will still exist.
In general, the with statement is bad, but it sounds like your use case might be one where it makes sense.
You can do it by using .call() and referencing the variable via this.xyz inside the function:
(function foo() {
console.log(this.bar);
}).call(myGlobalContext);
The only other way is by wrapping the function call in another scope:
(function() {
var bar = '123';
(function() {
console.log(bar);
})();
})();
You can do something like this by passing the namespace to the IIFE:
var myNamespace = { bar: "foo" };
(function( ns ) {
console.log( ns.bar );
}( myNamespace ));

Immediately-Invoked Function Expression (IIFE) vs not

I see a lot of code like:
var myApp ={};
(function() {
console.log("Hello");
this.var1 = "mark"; //"this" is global, because it runs immediately on load. Caller is global
myApp.sayGoodbye = function() {
console.log("Goodbye");
};
})();
Which causes the anonymous function to execute immediately. But what is the advantage of this, compared to just putting the code inline?
var myApp ={};
console.log("Hello");
var1 = "mark";
myApp.sayGoodbye = function() {
console.log("Goodbye");
};
Apparently it's to do with scope of the function, but as the function is anonymous and called by window, it's scope (i.e. this) is global, no?
Usually, you would have this :
var myApp ={};
(function() {
console.log("Hello");
var var1 = "mark";
myApp.sayGoodbye = function() {
console.log("Goodbye");
};
})();
The main difference is that var1 doesn't clutter the global namespace. After this call, var1 is still the same than before (generally undefined).
As var1 can only be accessed from the function defineds in the closure, it is said "private".
Apart avoiding possible causes of conflicts, it's just cleaner not to keep global variables when useless.
Here, you don't have a local variable but a global one defined as this.var1. It's probably a bug, or the reason would be found elsewhere in the code.
One reason: wrapping your code in an anonymous function allows you to create a module which distinguishes a public API from private functions and variables that are only used internally to the module. This avoids polluting the global namespace.
var myApp ={};
(function() {
console.log("Hello");
this.var1 = "mark";
function helper() {/*Some code here*/;}
myApp.sayGoodbye = function() {
helper()
console.log("Goodbye");
};
})();
I could say:
var myApp ={};
console.log("Hello");
var var1 = "mark";
function helper() {/*Some code here*/;}
myApp.sayGoodbye = function() {
helper()
console.log("Goodbye");
};
But then the global scope includes a function called helper which is of no use to anyone using your module, and could lead to possible naming conflicts with other modules.
I could alternatively just include helper as a method of myApp.
var myApp ={};
console.log("Hello");
var var1 = "mark";
myApp.helper = function() {/*Some code here*/;}
myApp.sayGoodbye = function() {
this.helper()
console.log("Goodbye");
};
However, I may wish to prevent users from directly calling helper, in which case this won't do.

Is it possible to pass execution context of the immediately invoked function expression

Consider the following code:
(function() {
var a = 5;
var someFunc = function() { ... };
function anotherFunc() {
...
};
})();
window.myGlobalObj = {
init: function() {
// and somehow here I want to access to the IIFE context
}
};
I want to have the execution context of IIFE in my global object. I do have access to function expression and object itself so I can pass or modify something to make it work (and no, I can't rewrite everything inside the object or function).
Is it even possible?
The only way I see how that's poosible is by using eval to simulate dynamic scopes. Do this (note that the IIFE must be placed after the global object):
window.myGlobalObj = {
init: function() {
// and somehow here I want to access to the IIFE context
}
};
(function() {
var a = 5;
var someFunc = function() { ... };
function anotherFunc() {
...
};
eval("(" + String(window.myGlobalObj.init) + ")").call(window.myGlobalObj);
})();
Here's a reference as on how to use dynamic scopes: Is it possible to achieve dynamic scoping in JavaScript without resorting to eval?
Edit: I've included an example to demonstrate the power of using dynamic scopes in JavaScript. You can play with the fiddle too.
var o = {
init: function () {
alert(a + b === this.x); // alerts true
},
x: 5
};
(function () {
var a = 2;
var b = 3;
eval("(" + String(o.init) + ")").call(o);
}());
The "contents" of your IIFE, i.e., a, someFunc, etc., are local to that function scope, so you can only access them within that scope. But you can assign window.myGlobalObj inside the IIFE:
(function() {
var a = 5;
var someFunc = function() { ... };
function anotherFunc() {
...
};
window.myGlobalObj = {
init: function() {
// and somehow here I want to access to the IIFE context
}
};
})();
Then the init function will have access to those variables since they are in its containing scope.
EDIT: if you can't move the definition of myGlobalObj into the IIFE the only thing I can think of is to use the IIFE to create a second global object that you access from myGlobalObj:
(function() {
var a = 5;
var someFunc = function() { ... };
function anotherFunc() {
...
};
// create a global object that reveals only the parts that you want
// to be public
window.mySecondObject = {
someFunc : someFunc,
anotherFunc : anotherFunc
};
})();
window.myGlobalObj = {
init: function() {
window.mySecondObject.someFunc();
}
};
No. It is not possible. The context you want to access is called closure and can be accessed only within the function (in your case, the anonymous function (IIFE how you call it)). For more about closures follow the excellent Douglas Crockfords The Javascript programming language video tutorial.
You will have to place those attributes to some shared object.

Scope of self-invocation function in Javascript

Why does self-invocation function inside a function don't get the scope of the outer function in JavaScript?
var prop = "global";
var hash = {
prop: "hash prop",
foo: function(){
console.log(this.prop);
(function bar(){
console.log(this.prop);
})();
}
};
var literal = {
prop: "object"
};
hash.foo();
// hash prop
// global
hash.foo.call(literal);
// object
// global
Looks like altering the scope of the outer function has no effect on the scope of the inner self-invocation function.
PS: The question is not about how to alter the scope of the inner function. But what is the proper explanation in the "Javascript language" perspective? Does all self executing functions have 'global' scope by default? If so, why?
Your problem is the this and what it references:
foo: function(){
console.log(this.prop);
(function bar(){
console.log(this.prop); <--- this does not reference to foo here, but instead it refers to the window object
})();
}
You need to keep a reference to the outer this:
foo: function(){
console.log(this.prop);
var that = this;
(function bar(){
console.log(that.prop); <--- tada!
})();
}
Update
Some explanation. It's all about how JavaScript determines the context when invoking a function.
function Test() {
this.name = "Test";
this.bar = function() { console.log("My name is: "+ this.name);}
}
function Blub() {
this.name = "Blub";
this.foo = function() { console.log("My name is: " + this.name);}
}
var a = new Test();
var b = new Blub();
// this works as expected
a.bar(); // My name is: Test
b.foo(); // My name is: Blub
// let's do something fun
a.foo = b.foo; // make an educated guess what that does...
a.foo() // My name is: Test
Huh? Aren't we referencing the method of Blub? No we're not. We are referencing the unbound function of Blub.
JavaScript binds on . (dots) and based on that it decides waht the value of this should be.
Since you're not calling your anonymous function on an object (therefore no .) it will make this reference to the global object, which is - in case of the browser - the window object.
Another example (one might think this would work):
var str = "Hello World";
var ord = str.charCodeAt; // let's make a little shortcut here.... bad idea
ord(0) // no dot...
Instead of the char codes that are in str we get the ones that are in the global object, of course that's not a string so charCodeAt calls toString on which results in "[object DOMWindow]"
You are not applying any object as the this context when you call the inner function, so it gets this set to window by default. If you wanted to call the closure with the same this as the outer function, you would have to do:
(function bar(){
console.log(this.prop);
}).call(this);
Or:
var that = this;
(function bar(){
console.log(that.prop);
})();

Categories