how do i expose function from anonymous self invoking function? - javascript

(function(){
var a = function () {
alert("hey now!! ");
};
return {"hi":function(){return a;}};
})();
hi();
This code doesn' t work. How do i expose a function??

The self invoking function returns an object with the property hi, this object is not added to the global scope so that you can use the property directly. Put the result of the function in a variable:
var o =
(function(){
var a = function (){
alert("hey now!! ");
};
return {"hi":function(){return a;}};
})();
Using the property to call the function will only return the function contained in the variable a, so you have to call the return value from the function to call the function that contains the alert:
o.hi()();
Demo: http://jsfiddle.net/Guffa/9twaH/

There are two basic ways:
var MyNameSpace = (function(){
function a (){
alert("hey now!! ");
};
return {a: a};
})();
MyNameSpace.a();
or
(function(){
function a (){
alert("hey now!! ");
};
MyNameSpace = {a: a};
})();
MyNameSpace.a();
I prefer the 2nd way since it seems cleaner
It is called the "revealing module pattern" btw, which you can read up on to understand it better :)
https://addyosmani.com/resources/essentialjsdesignpatterns/book/#revealingmodulepatternjavascript

var obj = (function(){
var a= function (){
alert("hey now!! ");
};
return {"hi":function(){return a;}};
})();
obj.hi()

You have to assign the return value of the anonymous function to a variable in the current scope:
var f = (function() {
var a = function() {
alert("hey now!! ");
};
return {
"hi": function() { return a; }
};
})();
f.hi()();

It?
(function(){
var a = function () {
alert("hey now!! ");
};
return {"hi":function(){return a;}};
})().hi()();

I suppose in order to expose the function, instead of its code, the syntax should be
var obj2 = (function(){
var a= function (){
alert("hey now!! ");
};
return {"hi":a};
})();
alert(obj2.hi());

Or you could wrap your 'hi' function in an IIFE like so...
var myFunction = (function(){
var a = function () {
alert("hey now!! ");
};
return {
"hi": (function(){
return a;
}())
};
})();
myFunction.hi();

Related

return a variable from a function javascript

how do I return a variable from a function and assign it to an object as a property? I wrote this code but it says that the object property is undefined
var ahoy = (function yes() {
var mp = {};
function oh() {
var greeting = "hello";
var advoir = "goodbye";
}
return {
greeting: greeting,
advoir: advoir
};
oh();
mp.greeting = greeting;
mp.advoir = advoir;
console.log(mp.greeting);
console.log(mp.advoir);
});
ahoy();
The error here arises from the fact that the ahoy function does not have access to the variables in the scope of oh.
function oh() {
var greeting = "hello";
var advoir = "goodbye";
console.log(greeting); // "hello"
}
oh();
console.log(greeting); // undefined
greeting is local to the scope of oh since it is declared inside of oh, and is thus not accessible outside of that function. Instead, this would work:
var greeting;
console.log(greeting); // undefined
function oh() {
greeting = "hello";
console.log(greeting); // "hello"
}
console.log(greeting); // undefined
oh();
console.log(greeting); // "hello"
move return statement to the bottom. define greeting outside of the oh function(define with var mp)
Instead of executing a function, you can just define the variables and return the object all at once
var ahoy = (function yes() {
return {
greeting: "hello",
advoir: "goodbye"
};
});
ahoy();
console.log(ahoy());
I can see few issues in your code:-
You are assigning "hello" to greeting and "goodbye" to advoir in function oh() and return in outside that function.
Now say even if you put return inside the function oh(), your greeting and advoir would be returned, but you are not capturing the output and thus greeting shows undefined.
You can try following:-
var ahoy = (function yes() {
function oh() {
var mp={
greeting:'greeting',
advoir:'advoir'
}
return mp;
}
mp=oh();
var greeting = mp.greeting;
var advoir = mp.advoir;
console.log(mp.greeting);
console.log(mp.advoir);
});
ahoy();
Jsfiddle link
Try this
var ahoy = (function yes() {
var mp = {};
// declare the variable outside of function oh
var greeting, advoir;
function oh() {
greeting = "hello";
advoir = "goodbye";
}
oh();
mp.greeting = greeting;
mp.advoir = advoir;
console.log(mp.greeting);
console.log(mp.advoir);
// move return statement to end of function
return {
greeting: greeting,
advoir: advoir
};
});
ahoy();

IIFE, javascript, function undefined

This is my IIFE function
var test = function(){
console.log('fire');
}();
It invokes at start. But how do I call this again?
var fireTestFn = function(){
test();
}
fireTestFn(); // test() is not a function
JSbin https://jsbin.com/cesuzimogu/edit?js,console
You could return test from inside using a named function expression.
var test = function fn(){
console.log('fire');
return fn;
}();
The result of the IIFE will be assigned to test, which is obviously not a function, because you're not returning a function from the IFEE (or anything for that matter). Keep it simple; what you want is a named function you can call anytime as many times as you want:
function test() {
console.log('fire');
}
test(); // call as often as you want
Something like this will work
var myNamespace = {};
(function(ns) {
ns.test = function(){
console.log('fire');
};
/*ns.myOtherFunction = function(var1) { }*/
})(myNamespace);
var fireTestFn = function(){
myNamespace.test();
};
fireTestFn();
See example here: https://jsbin.com/helumoveqe/edit?js,console
As the error says
test() is not a function
When you self-invoked the function, the result was stored into test.
In order to be able to use test as a function and call repeatedly elsewhere, do not self-invoke
var test = function(){
console.log('fire');
};
or have the function return an inner function
var test = function () {
return function () {
console.log('fire');
}
};

variable gets assigned function

My English = Google Translate. Sorry :(
function XXX(){
abc = function(){return 'Message';}
return abc;
}
function Alerttt(){
var AlertText= XXX();
alert(AlertText);
}
Result:
AlertText = function(){return 'Message';}
I want to:
AlertText = Message
How can I do?
You'll have to call the function.
function XXX() {
abc = function() {
return 'Message';
}
return abc;
}
function Alerttt() {
var AlertText = XXX();
alert(AlertText()); // call it
}
Alerttt();
You can also do var AlertText = XXX()(); so that AlertText gets the return value from the called function so you can just do alert(AlertText);
Are you looking for this?
function XXX()
{
abc = function(){return 'Message';}
return abc;
}
function Alerttt()
{
var AlertText = XXX()();
alert(AlertText);
}
Alerttt();
Calling XXX returns a function object, so XXX() is a function object, and you need to call that function object as XXX()() to return 'Message'.

Chain calls to the same function and modify an internal variable

Is this possible with javascript? Use the same function and call it again and again.
myFunc("test")("me")("please")()
EDIT
Thanks for the answers. I'd like to keep and internal variable that appends the string to the previous one if possible.
function MyFunc(arg){
console.log(arg);
return MyFunc;
}
MyFunc("a")("b")("c");
JsFiddle example
Y-combinator example:
function Y(f) {
var g = f(function() {
return g.apply(this, arguments);
});
return g;
}
var MyFunc = Y(function(f) {
var a = "";
return function(n) {
a = a + n;
console.log(a);
return f;
};
});
//alert(a); // throws error as a is outside of scope here
MyFunc("a")("b")("c"); # logs a; ab; abc
Yes, you can, if you will return arguments.callee;, example:
(function(param){console.log(param); return arguments.callee;})("test")("me")("please")
will log into console:
test
me
please

Javascript pseudo-classes, jQuery event handlers and 'this'

I've got a big Javascript project that I'm trying to refactor into pseudo-classes:
jsFiddle: http://jsfiddle.net/waitinforatrain/7T42w/
var MyNameSpace = {}
MyNameSpace.MyClass = function() {
this.doSomething = function () {
return "hello";
}
this.doSomething2 = function() {
var x = this.doSomething() + " world";
alert(x);
}
this.doSomething2(); //Works fine
$("#mydiv").click ( this.doSomething2 ); //Doesn't work
}
var class = new MyNameSpace.MyClass();
The reason the click event causes an error is that this refers to the #mydiv element.
How am I supposed to design the above so that I can access the element that was clicked but can also call doSomething()?
You need to cache the context reference and wrap the call in a closure:
var MyNameSpace = {}
MyNameSpace.MyClass = function() {
var context = this;
context.doSomething = function () {
return "hello";
}
context.doSomething2 = function() {
var x = context.doSomething() + " world";
alert(x);
}
// You can do this:
context.doSomething2();
// Or this:
$("#mydiv").click(function(e) {
context.doSomething2();
});
}
this.doSomething2 = $.proxy(function() {
var x = this.doSomething() + " world";
alert(x);
}, this);
$.proxy binds the this scope to the context variable inside said function.
Save a reference to this in the outer scope:
MyNameSpace.MyClass = function() {
var that = this;
this.doSomething = function () {
return "hello";
}
this.doSomething2 = function() {
var x = that.doSomething() + " world";
alert(x);
}
this.doSomething2(); //Works fine
$("#mydiv").click ( this.doSomething2 ); //Doesn't work
}
The function assigned to doSomething2 is said to "close over" the variables in its lexical scope and so has access to their values even once MyClass has returned. This allows us to access the doSomething method through the reference to the instance we assigned to that.

Categories