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'.
Related
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();
I've an object looks like this:
var obj ={
property : '',
myfunction1 : function(parameter){
//do stuff here
}
}
I need to set some private properties and functions, which can not be accessed/seen from outside of the object. It is not working with
var property:, or var myFunction1
Next question is, if I call a function within or outside the object, I always have to do this with obj.myfunction(). I would like to asign "this" to a variable. Like self : this. and call inside the object my functions and variables with self.property and self.myfunction.
How? :)
There are many ways to do this. In short: If dou define a function inside another function, your inner function will be private, as long as you will not provide any reference to if.
(function obj(){
var privateMethod = function() {};
var publicMethod = function() {
privateMethod();
...
};
return {
pubMethod: publicMethod
}
}());
var obj = (function() {
var privateProperty;
var privateFunction = function(value) {
if (value === void 0) {
return privateProperty;
} else {
privateProperty = value;
}
};
var publicMethod = function(value) {
return privateFunction(value);
}
return {
getPrivateProperty: function() {
return privateFunction();
},
setPrivateProperty: function(value) {
privateFunction(value);
}
}
})();
obj.setPrivateProperty(3);
console.log(obj.getPrivateProperty());
// => 3
console.log(obj.privateProperty);
// => undefined
obj.privateFunction();
// => TypeError: undefined is not a function
Use closures. JavaScript has function scope, so you have to use a function.
var obj = function () {
var privateVariable = "test";
function privateFunction() {
return privateVariable;
}
return {
publicFunction: function() { return privateFunction(); }
};
}();
Calling a function from a Object Literal
var runApp = {
init: function(){
this.validate();
},
run: function() {
var myStr = "My Name";
var abc = function()
{
return myStr;
}
},
validate: function() {
var val = this.run().abc(); // It Gives "Uncaught TypeError: Cannot call method 'abc' of undefined "
alert(val);
}
};
runApp.init();
How to Call the function abc() inside the function validate?
Function abc is defined within the scope of "run" on thus will not be accessible from another function. If you really want this, you could make "abc" available on the "this" scope.
var runApp = {
init: function(){
this.validate();
},
run: function() {
var myStr = "My Name";
this.abc = function() {
return myStr;
}
},
validate: function() {
this.run(); // run this one first so function abc exists
var val = this.abc();
alert(val);
}
}
runApp.init();
So in short: you cannot do this without modifying the code itself.
You can return abc function from run function inside an object:
run: function() {
var myStr = "My Name";
var abc = function() {
return myStr;
}
return { abc : abc };
}
and then this.run().abc() will work.
Since your run method does not return an object which contains the abc function you are not able to call it. It returns undefined instead.
One solution to this is if you return an object which has a method named abc.
I think I understand why variables exist outside of the function they were declared in, because you're returning another function:
myFunction = function() {
var closure = 'closure scope'
return function() {
return closure;
}
}
A = myFunction(); // myFunction returns a function, not a value
B = A(); // A is a function, which when run, returns:
console.log(B); // 'closure scope'
The way that it's written now, calling A() is like a getter.
Q: How can I write myFunction so that calling A(123) is a setter?
Try the following:
myFunction = function() {
var closure = 'closure scope'
// value is optional
return function(value) {
// if it will be omitted
if(arguments.length == 0) {
// the method is a getter
return closure;
} else {
// otherwise a setter
closure = value;
// with fluid interface ;)
return this;
}
}
}
A = myFunction(); // myFunction returns a function, not a value
A(123); // set value
B = A(); // A is a function, which when run, returns:
console.log(B); // '123'
You could do something like this if you want both getter and setter for example:
var func = function() {
var closure = 'foo';
return {
get: function() { return closure; },
set: function(value) { closure = value; }
}
};
var A = func();
A.set('foobar');
console.log(A.get()); //=> "foobar"
Should be as simple as:
myFunction = function() {
var closure = 'closure scope'
return function(setTo) {
if (typeof setTo !== "undefined") {
closure = setTo;
return this; //support call chaining, good idea hek2mgl
} else {
return closure;
}
}
}
Since the closure variable is within the closure of the function's scope, you should be able to assign to it the same way you can read from it.
See jsFiddle: http://jsfiddle.net/WF4VT/1/
Another alternative would be to use a class and define getters and setters:
function MyClass(p){
this._prop = p;
}
MyClass.prototype = {
constructor: MyClass,
get prop(){
return this._prop;
},
set prop(p){
this._prop = p;
}
}
var myObject = new MyClass("TEST");
console.log(myObject.prop);
myObject.prop = "test";
console.log(myObject.prop);
Demo: http://jsfiddle.net/louisbros/bMkbE/
jsFiddle Demo
Have your returned function accept an argument. Use it as a setter:
myFunction = function() {
var closure = 'closure scope';
return function(val) {
closure = val;
return closure;
}
}
A = myFunction(); // myFunction returns a function, not a value
B = A(123); // A is a function, which when run, returns:
console.log(B); // 'closure scope'
Revisiting this question, I see that I could do it this way:
function outside() {
var result = 'initialized'
return inside
function inside(argVariable) {
if(arguments.length) {
result = argVariable
return this
} else {
return result
}
}
}
myFunction = outside() // outside returns a function
X = myFunction() // returns: 'initialized'
$('body').append(X + '<br>')
myFunction(123) // setter
X = myFunction() // returns: 123
$('body').append(X)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
(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();