Reputation: 11
In the below code
(function x() {
var j = function() { alert("234234"); }
return {
s: j
}
})()
var x1 = new x();
x1.s();
How to invoke the method j()? Or before that i should be asking, is there a way to create an instance of the function x() because that is what is happening. Please see the fiddle http://jsfiddle.net/e5k6bdvn/
Upvotes: -1
Views: 2951
Reputation: 546
As stated by @epascarello, it's hard to say what is the context of your question.
If the meaning of x
is to return objects more than once, you should not immediately invoke it. Instead you need only to declare it:
function x () { return { j: function () { alert("234234") } } }
then call it whenever you want, and invoke j
.
var x1 = x();
x1.j();
If instead you're planning to use x
only once, it's nice to invoke it immediately, but you need to consume the call to j
immediately too.
(function () {
return {
j: function () {
alert("234234")
}
}
})().j();
Upvotes: 1
Reputation: 943100
new
)Such:
var x = (function () {
var j = function() { alert("234234"); };
return {
s: j
};
})();
x.s();
Or, if you want to create multiple objects in the same way:
x
as many times as you likeSuch:
function x () {
var j = function() { alert("234234"); };
return {
s: j
};
};
var x1 = x();
var x2 = x();
x1.s();
Or, if you want to create a constructor function:
Such:
function x () {
};
x.prototype.s = function () {
alert("234234");
}
var x1 = new x();
var x2 = new x();
x1.s();
Upvotes: 8