I have the below code:
filtersManager = (function ($) {
var that = this;
function configure() {
// some work
return that;
};
function process() {
// some work
return that;
}
return {
// public functions
configure: configure,
process: process
};
}(jQuery));
but when it's called using the below it fails:
filtersManager.configure().process();
Error: Object doesn't support property or method 'process'
whereas the below works:
filtersManager.configure();
filtersManager.process();
You are returning the wrong thing (this in a plain function invocation is the global object). You want to return the object that you originally created, which I will call the interface.
filtersManager = (function ($) {
var interface = {
// public functions
configure: configure,
process: process
};
function configure() {
// some work
return interface;
};
function process() {
// some work
return interface;
}
return interface;
}(jQuery));
If you're wondering why I can reference the functions defined below, it's due to hoisting.
Immediate function is executed in global object (window) context. Try something similar to this:
filtersManager = (function ($) {
var that = {};
that.configure = function() {
// some work
return that;
};
that.process = function() {
// some work
return that;
}
return that;
}(jQuery));
UPD. Based on comments
Constructor pattern seems to fit your need better:
var FiltersManager = (function($) {
function FiltersManager() {}
FiltersManager.prototype = {
configure: function() {
console.log('configure');
return this;
},
process: function() {
console.log('process');
return this;
}
}
return FiltersManager;
}(jQuery));
new FiltersManager().configure().process();
As to continue what others have said , I think you confused with the function constructor syntax which would work , similar to what you've said ;
var G=function g()
{
this.configure =function (){return this;}
this.process =function (){return this;}
};
var _= new G();
console.log(_.configure().process())
If you wanted to re-use the functions on other objects too, you could do it like this
filtersManager = function ($) {
function configure() {
// some work
return this;
};
function process() {
// some work
return this;
}
return {
// public functions
configure: configure,
process: process
};
}(jQuery);
(OTOH, if you wanted to create aliases to them, you would then have to bind them to the object)
Or if configure and process are quite short, simple functions :
filtersManager = (function ($) {
return {
// public functions
configure: function () {
// some work
return this;
},
process: function () {
// some work
return this;
}
};
}(jQuery));
Related
Let's say I have a function made up of private and public methods, like this:
(function () {
var private_var = "hey";
function private_function () {
// stuff
}
stuff = {
public_var: "hey",
public_function: function () {
// this can be called from the outside with no prob.
},
do_this_now_and_later: (function dothis() {
// i could call this from the namespace "dothis()"
// but not the method name, stuff.do_this_now_and_later()
})()
}
})(window.load = window.load || {});
i want to execute the function do_this_now_and_later() as soon as it's rendered, but again later as well.
if i wrote this example code correctly, one should be able to call that function by the namespace dothis(), but is it possible to call that function by its method?
Try to return dothis() in your function.
(function () {
var private_var = "hey";
function private_function () {
// stuff
}
stuff = {
public_var: "hey",
public_function: function () {
// this can be called from the outside with no prob.
},
do_this_now_and_later: (function dothis(v) {
alert(v);
return dothis;
// i could call this from the namespace "dothis()"
// but not the method name, stuff.do_this_now_and_later()
})('foo')
}
stuff.do_this_now_and_later('bar');
})(window.load = window.load || {});
I spent the better part of the day reading about the module pattern and its 'this' scope. Eventually I found a work-around for my problem, although with a feeling there's a better way of doing things.
The actual code is >200 lines, but I've boiled it down to the following:
objA has a method (publicA) that objB wants invoke by callback. The detail that complicates things is that publicA needs help from publicA_helper to do its job. (http://jsfiddle.net/qwNb6/2/)
var objA = function () {
var privateA = "found";
return {
publicA: function () {
console.log("privateA is " + this.publicA_helper());
},
publicA_helper: function () {
return privateA;
}
};
}();
var objB = function () {
return {
callback: function (callback) {
callback();
}
}
}();
objA.publicA(); // privateA is found
objB.callback(objA.publicA); // TypeError: Object [object global]
Fair enough – I've grasped that the caller's context tends to influence the value of 'this'. So I add measures to retain 'this' inside objA, of which none seems to work. I've tried the
var objA = (){}.call({}) thingy, setting var self = this; (calling self.publicA_helper() accordingly). No luck.
Eventually, I added a private variable var self;, along with a public method:
init: function() {self = this;},
...and by making sure I call objA.init(); before passing objA.publicA to objB.callback, things actually work.
I cannot stress the immensity of the feeling that there's a better way of doing this. What am I missing?
The generalized solution is extremely simple.
Write all the module's methods as private, then expose those that need to be public.
I write all my modules this way :
var objA = function () {
var privateA = "found";
var A = function () {
console.log("privateA is " + A_helper());
},
var A_helper = function () {
return privateA;
}
return {
publicA: A
//A_helper need not be exposed
};
}();
Thus, all methods are in the same scope, each one having direct access to all other methods in the same module, and the ambiguous this prefix is avoided.
objB.callback(objA.publicA); will now work as expected.
See fiddle
I've tried the var objA = (){}.call({}) thingy,
How? You want to use call on the callback that you want to invoke with a custom this, not on your module closure. It should be
var objB = {
callback: function (callback, context) {
callback.call(context);
}
};
objB.callback(objA.publicA, objA);
I've tried setting var self = this;
The self variable is supposed to be in a closure and point to the object on the methods are stored. That is only this when your module IEFE would be invoked on your module - it's not. Or if it was a constructor - it's not. You could change that with call as above:
var objA = function () {
var privateA = "found",
self = this;
this.publicA = function () {
console.log("privateA is " + self.publicA_helper());
};
this.publicA_helper = function () {
return privateA;
};
return this;
}.call({});
But that's ugly. In your case, the self variable simply needs to point to the object literal which you're returning as your module:
var objA = function () {
var privateA = "found",
self;
return self = {
publicA: function () {
console.log("privateA is " + self.publicA_helper());
},
publicA_helper: function () {
return privateA;
}
};
}();
Btw, since you're creating a singleton you don't need an explicit self, you could just reference the variable that contains your module (as long as that doesn't change):
var objA = function () {
var privateA = "found";
return {
publicA: function () {
console.log("privateA is " + objA.publicA_helper());
},
publicA_helper: function () {
return privateA;
}
};
}();
Another method would be to simply make all functions private and then expose some of them - by referencing them local-scoped you will have no troubles.
var objA = function () {
var privateA = "found";
function publicA() {
console.log("privateA is " + helper());
}
function helper() {
return privateA;
}
return self = {
publicA: publicA,
publicA_helper: helper // remove that line if you don't need to expose it
};
}();
The reason is that the context is getting changed when you are invoking the callback. Not a generalized solution, but shows that the code works by specifying the context while invoking callback.
var objA = function () {
var privateA = "found";
return {
publicA: function () {
console.log("privateA is " + this.publicA_helper());
},
publicA_helper: function () {
return privateA;
}
};
}();
var objB = function () {
return {
callback: function (callback) {
callback.call(objA);
}
}
}();
objA.publicA(); // privateA is found
objB.callback(objA.publicA); // privateA is found
Im working in a sub-module pattern code. Want to create sub-modules with objects literals, the problem is this for the objects inside the sub-module is MODULE and not my object literal. Any idea?
var MODULE.sub = (function () {
var myObject = {
key: value,
method: function () {
this.key // this = MODULE and not MyObject... :(
}
};
return myObject.method;
}(MODULE));
This works for me:
var MODULE = MODULE || {};
MODULE.sub = (function () {
return {
myObject : {
key : 10,
method : function() {
console.log(this.key);
}
}
};
})();
Then call it:
MODULE.sub.myObject.method();
You were only returning the method and not the key so "this" would be undefined. You could keep it private if you want like this and pass key in as a var:
var MODULE = MODULE || {};
MODULE.sub = (function () {
var key = 10,
return {
myObject : {
method : function() {
console.log(key);
}
}
};
})();
Solved... just return a function in MODULE.sub calling the public method. I don't know if is the best approach
var MODULE.sub = (function () {
var myObject = {
key: value,
method: function () {
this.key // this = myObject :)
}
};
return function () {
myObject.method();
}
}(MODULE));
The this keywords value depends on how the function is called. So if you assign that function to MODULE.sub, and then invoke it as MODULE.sub(…), then this will point to the MODULE of course. If you had invoked it as myObject.method(…), then this would point to that object.
So you either should expose the whole myObject (like in #BingeBoys answer), or do not export that function and expect it to be a method of myObject. Instead, you could use a bound one:
return myObject.method.bind(myObject);
or the explicit equivalent of that
return function() {
return myObject.method();
};
or you would not put the function as method on that object at all:
…
var myObject = {
key: value,
};
return function() {
myObject.key // no `this` here
…
};
…
I've got an enclosed function in JavaScript like so:
var myFunction = function (options) {
function blah() {
var blahString = options.blahString;
//more blah
}
function blah2() {
//blah2
}
return {
blah : function { return blah(); },
blah2 : function { return blah2(); }
}
};
When I'm in my HTML, I'm trying to call myFunction.blah() and it's telling me the object has no method 'blah'.
How do I access the returned functions in the global scope?
Thanks!
This just explains why it doesn't work and how to make it work. For learning things this would be enough. Actually you should explain what you are trying to achieve so that others can guide you in the right direction.
// A scope of a function is activated ONLY when it is invoked
// Let us define a function
var myFunction = function (options) {
function blah() {
alert("I am blah");
}
function blah2() {
//blah2
}
alert("I am active now and I am returning an object");
return {
blah: function () {
return blah();
},
blah2: function () {
return blah2();
}
};
};
myFunction.blah3 = function () {
alert("I am blah3");
};
// myFunction is not invoked, but justed used as an identifier.
// It doesn't have a method blah and gives error
myFunction.blah();
// blah3 is a static method of myFunction and can be accessed direclty using myFunction
myFunction.blah3();
// myFunction is invoked, which returns an object
// it contains the function blah
myFunction().blah();
// or
var myObject = myFunction();
myObject.blah();
myObject.blah2();
var myFunction = (function (options) {
function blah() {
return options.a;
}
function blah2() {
//blah2
}
return {
blah: function() { return blah(); },
blah2: function() { return blah2(); }
};
});
alert(myFunction({a:1, b:2}).blah());
This works fine. Note blah: function <-- needs ()
see http://jsfiddle.net/kw6fJ/1
I have the following code
var PROMO = PROMO || {};
PROMO.Base = (function () {
var _self = this;
var Init = function () {
WireEvents();
};
var WireEvents = function () {
//wire up events
};
} ());
In the same file I have the code to call the above function
I am trying to get to an end point where I can use the following code
$(document).ready(function () {
PROMO.Base.Init();
});
this gives the error
Cannot call method 'Init' of undefined
Now I know there are many ways to write javascript, but in this case I want to be able to call my functions, or least the Init method in the way shown above.
var PROMO = PROMO || {};
PROMO.Base = (function () {
var _self = this;
var Init = function () {
WireEvents();
};
var WireEvents = function () {
//wire up events
};
var reveal = {
Init: Init
};
return reveal;
} ());
You need to return the public facing functions. See updated code.
Working fiddle with both patterns, using IIFE and direct attribution.
Using var makes the definition private and your function is returning nothing. Use this:
PROMO.Base = {
Init: function() {
},
WireEvents: function() {
};
};
You are wrapping the definition with an IIFE(Immediately Executed Function Expression). So your PROMO.Base object will be assigned the value of that (function(){//blabla})(); returns. But your function doesn't have a return statement. By default it will return undefined.
Which is way your PROMO.Base will be undefined and you get this:
Cannot call method 'Init' of undefined
If you really want that IIFE:
var PROMO = PROMO || {};
// NEVER use _self = this inside static functions, it's very dangerous.
// Can also be very misleading, since the this object doesn't point to the same reference.
// It can be easily changed with Function.prototype.call and Function.prototype.apply
PROMO.Base = (function () {
_PROMO = {
Init : function () {
document.body.innerHTML += "itworks";
},
WireEvents : function () {
//wire up events
}
}
return _PROMO;
} ());
PROMO.Base.Init();
Update
The better and easier pattern is to simply assign the functions to PROMO.Base. Dully note you should not capitalize static functions, but only constructors. So if something is not meant to be instantiated, don't call it Init, it should be init. That is the convention.
var PROMO = {};
PROMO.Base = {};
PROMO.Base.init = function() {
console.log("this works");
};
PROMO.Base.wireEvents = function() {
console.log("this is a static function too");
};
You can attach it to the window object like ...
window.PROMO = (function($, _){
// this will access PROMO.Base
PROMO.Base = {
// inner functions here
Init:{}
};
})(jQuery, _);
Then load it as you do.
Or if you depend from jQuery
(function($){
var PROMO = {
// inner functions
Init: function(){},
WireEvents: function(){}
};
$.PROMO = PROMO;
})(jQuery);
On DOM ready
jQuery(function ($) {
var promo = $.PROMO || undefined;
promo.Base.Init();
});