Access of function in jQuery scope - javascript

I want to build a function outside a jQuery scope:
(function($) {
function MyObject() {
console.log('foo');
};
}(jQuery));
var $my_object = new MyObject();
But function MyObject is not accessible :
ReferenceError: MyObject is not defined
However, if i build my function in the scope, it's working:
(function($) {
function MyObject() {
console.log('foo');
};
var $my_object = new MyObject();
}(jQuery));
foo
How access to MyObject outside the scope ?

I would probably not recommend it but you can basically do what you want by returning the functions as part of an object and assigning the IIFE to a variable like this
var library = (function ($) {
var exports = {};
var private = 'see you cant get this';
var MyObject = exports.MyObject = function (_in) {
console.log(_in);
};
var another_func = exports.sum = function (a, b) {
console.log(a + b);
};
return exports;
}(jQuery));
library.MyObject('foobar'); // "foobar"
library.sum(3, 5); // 8
console.log(private); // Uncaught ReferenceError: private is not defined

Although I don't know why you want to do it.. Maybe this helps
// Define Class globally
// window.MyObject also works
var MyObject = (function($) {
// Passes jQuery in
return function () {
console.log('foo');
};
}(jQuery));
var $my_object = new MyObject();

Related

How to run string as function inside a function in javascript?

An example of this question is like this
var bar = (function(){
function foo(){
alert("foo");
}
function test(){
var f = "foo";
// I want to run f() to run the function foo
}
})();
If the function is in the global scope I can run it using window["foo"]() or if namespaced window["namespace"]["foo"]() but how can I run it inside like the example? I don't want to use eval().
A much clear example of what I want is like this:
var fns = ['a','b','c'],
bar = (function(){
function a(){
alert("a");
}
function b(){
alert("b");
}
function c(){
alert("c");
}
function test(array){
for(var i;i<array.length;i++){
//I want to run the functions that is on the array
// something like window[array[i]]() if function is in the global scope
}
}
return {
test : test
}
})();
bar.test(fns);
You can create a local object to reference the function, then access its property as you would with your window example.
var bar = (function(){
function foo(){
alert("foo");
}
var obj = {
foo: foo
};
function test(){
var f = obj["foo"];
f();
}
test();
})();
That's as close as you're going to get in a local scope without using eval.
You can create the object OR fn with this operator and make it an function with new constructor.
Creating an object.
https://jsfiddle.net/0Lyrz6rm/6/
var bar = {
foo: function(){
alert("foo");
},
test: function(){
var f = "foo";
return f;
}
}
bar["foo"]();
console.log(bar["test"]());
Another alternate way is to define the function as with constructor and little modification.
https://jsfiddle.net/0Lyrz6rm/4/
var bar = function(){
this.foo = function(){
alert("foo");
};
this.test = function(){
var f = "foo";
return f;
// I want to run f() to run the function foo
}
this.test2 = {
f: "foo"
}
}
var f = new bar();
f["foo"]();
console.log(f.test());
console.log(f.test2.f);

Passing information between JavaScript methods

I have an object with two different sets of objects inside:
var myObj;
(function (myObj) {
var myFunction = (function () {
function myFunction(){
this.myValue = "something";
}
myFunction.getValue = function () {
var _this = this;
return _this.myValue;
}
return myFunction;
})();
myObj.myFunction = myFunction;
var myFunction2 = (function () {
function myFunction2() {
}
myFunction2.prototype.something = function () {
var a = myFunction.getValue();
}
return myFunction2;
})();
myObj.myFunction2 = myFunction2;
})(myObj || (myObj = {}));
Every time I run myFunction2.something(), a is assigned: undefined.
How can I get the value from myFunction into myFunction2.something()?
There is quite a mixup of scopes and design patterns in your code. Having 2 functions named the same way on inside the other creates different scopes for that name depending on where you call them. This quickly gets out of control. Like in this part:
var myFunction = (function () { // this guy is named myFunction
function myFunction(){ // this guy is also named myFunction
this.myValue = "something"; // 'this' here most certainly refers to 'window', not myFunction. Unless you do a 'new myFunction()' a la prototype
}
myFunction.getValue = function () {
var _this = this;// same here
return _this.myValue;
}
return myFunction;// here you are returning a function, not an object with methods
})();
Also I noticed that you are handling some logic with prototypes and other with closures, this also is kinda confusing when someone else (or you in a couple of months) need to refactor this code.
myFunction.getValue = function () {
var _this = this;
return _this.myValue;
}
return myFunction;
You could go all prototypes or all closures. I prefer closures so here is what I would do.
var myObj;
(function (myObj) {
// in this closure, we create a scope and return only the public methods
var myFunction = (function () {
// define properties here
var myValue = 'default value';
// define your methods, here we return
// myValue declared on the parent scope
function getValue() {
return myValue;
}
// this acts as a constructor, it autoexecutes
(function init(){
myValue = "something";
})();
// return all the functions in this scope
// you want to expose
return {
getValue: getValue
};
})();
// we then put myFunction into myObj
// at this point myFunction is an object with a method called getValue()
myObj.myFunction = myFunction;
var myFunction2 = (function () {
function something() {
// once this guy is called, we get the value from the other 'class'
var a = myFunction.getValue();
alert(a);// voila!
}
(function myFunction2() {
// do your init stuff here
})();
return {
something: something
};
})();
myObj.myFunction2 = myFunction2;
})(myObj || (myObj = {}));
// at this point myObj is an object with 2 'classes', each 'class' has its own methods
// we can proceed and call the desired method
myObj.myFunction2.something();
Demo: http://jsfiddle.net/bzw9kse7/
I've stepped through your code and just noticed a couple small things you're doing wrong.
You appear to be misdefining myFunction slightly, because it's not going to have myValue as a member variable, just a temporary variable that quickly falls out of scope. (And because it becomes undefined, it gets assigned to a, which is then unassigned).
So, replace these lines:
var myFunction = (function () {
function myFunction(){
var myValue = "something";
}
myFunction.getValue = function () {
var _this = this;
return _this.myValue;
}
return myFunction;
})();
With this:
var myFunction = (function () {
var myFunction = {};
myFunction.myValue = "something";
myFunction.getValue = function () {
var _this = this;
return _this.myValue;
}
return myFunction;
})();
EDIT Sorry, got this all wrong. It returns undefined because getValue is a static method of myFunction Object, not an instance method. That means that the this is not the same as in myFunction constructor.
Moreover you are not even attaching myValue to the this anywhere...
Edit 2 I added getMyValue to the myFunction prototype.
Try this:
....
var myFunction = (function () {
function myFunction(){
this.myValue = "something";
}
myFunction.prototype.getValue = function () {
return this.myValue;
}
// this creates the instance of the myFunction class.
return new myFunction();
})();
myObj.myFunction = myFunction;
...
// now you should be able to see the right result
var a = myFunction.getValue();
This is one of the craziest code I have ever seen, but the answer is this:
var a = myFunction.getValue(); is undefined because your 2nd definition of myFunction returns undefined, as in here:
function myFunction(){
var myValue = "something";
}
Your 2nd definition of myFunction actually replaces the 1st. See the comments below:
var myFunction = (function () {
// this definition replaces the one above
function myFunction(){
var myValue = "something";
}
myFunction.getValue = function () {
var _this = this;
return _this.myValue;
}
// which makes this return to not be taking in account when you are
// calling myFunction()
return myFunction;
})();

How to extend an object inside an anonymous function

I want to add another function called myFunction() into the CoreTeamObject, which is declared as local inside the anonymous function. Is this possible?
!function ($) {
var CoreTeamObject = function () {
var coreTeamVar1; // ...
this.someState = false; // ...
coreTeamFunction: function () { /* ... */ }
};
}(window.jQuery);
Normally, I'd use prototype with something like:
CoreTeamObject.prototype.myFunction = function(){
return
};
But I simply don't know how to access the object.
You simply can't. Variables within a function are private and cannot be accessed from the outside.
! function () {
var foo = 1;
}();
// Calling `foo` will throw a referenceError here.
// It doesn't even work with classes...
var foo = function () {
var bar = 2;
};
var bax = new foo();
// `bax.bar` doesn't exist.
However, there are workarounds. You could store them in a global variable (bad idea, though):
! function (w) {
w.foo = 3;
}(window);
// window.foo = 3
// foo = 3
Or if you can rewrite it to a class:
var foo = function () {
this.bar = 4;
};
var bax = new foo();
// bax.bar = 4
I hope this helps.

Creating global API object

I'm using the module-via-anonymous-function-pattern in java-script to have an anonymous function that embodies the whole module and exposes specific public API parts by setting a global property.
I tried several methods of setting such a global property and the second one posted below fails:
window.foo = (function() {
function bar() { this.hello = "world" }
return new bar();
})();
> foo.hello
"world" // OK
vs.
(function() {
window.foo2 = new bar( this.hello = "world" );
function bar() {}
})();
> foo2.hello
undefined // Fail
Why is the second method not creating a proper bar-object?
In your 2nd method:
(function() {
window.foo2 = new bar( this.hello = "world" );
function bar() {}
})();
this is the window, and
new bar(this.hello = "world")
is equal to
window.hello = "world";
new bar(window.hello);
you can check it here
And I think what you want is :
(function() {
window.foo2 = new bar( "world" );
function bar(a) {this.hello = a}
})();
see here
you should try the code below
(function() {
function bar() { this.hello = "world"; };
window.foo2 = new bar();
})();
The problem is the way to use construct an object. Try this two ways.
window.foo2 = new bar();
function bar() {this.hello = "world";};
or
window.foo2 = new bar("world");
function bar(x) {this.hello = x;};

Javascript Module pattern. How to access globals inside the module

I have seen the following code
var MODULE = (function () {
var my = {},
privateVariable = 1;
function privateMethod() {
// ...
}
my.moduleProperty = 1;
my.moduleMethod = function () {
// ...
};
return my;
}());
the properties can be accessed like MODULE.moduleProperty ...right?
But how to access globals privateVariable and privateMethod() inside the module(which are globals insode the module ...right?)
You can only access them from WITHIN the module code itself as such:
var MODULE = (function () {
var my = {},
privateVariable = 1;
function privateMethod() {
alert('this is private!');
}
my.moduleProperty = 1;
my.moduleMethod = function () {
privateMethod();
return privateVariable;
};
return my;
}());
Doing this:
MODULE.moduleMethod();
Will call private method (and alert 'this is private!') and return the value of privateVariable.
There is no way to access privateVariable or privateMethod outside the MODULE scope.
var MODULE = (function() {
//...declare your module as above
}());
console.log(MODULE.privateVariable); //logs undefined
Hopefully that helps clear it up for you.
No, they are not global, they are local variables inside the anonymous function.
You can access them from any code within the function, but outside the function they are not directly accessible.

Categories

Resources