function abc(){
//multiple variables and functions
a:function(){alert("a")};
}
function test(){
var k=abc();
k.a();
}
In the above case, I have a huge function abc() to be assigned to a variable. I want to call the member functions that are visible, like a() from the variable. Is this possible to implement and please give me a sample code if so.
When you include the parenthesis after your function, you're assigning the result of the function to your variable.
If you want to assign the function itself, just omit the parenthesis:
var k = abc;
k.a();
EDIT
Per #Kuba Wyrostek's answer, and #Pointy's comment, that a() function won't be properly exposed.
You'll need to take a look at the Module Pattern. What you need to do is to assign a function to a variable, and have that function return the functions that you want to be able to use outside of that function. This helps with encapsulation.
It's a little hard to tell from your code in the comment exactly what is the user-generated code, but I'll do my best.
var abc = (function () {
var grabApi,
initialize;
// Just an example of how to assign an existing function
// to a property that will be exposed.
grabApi = SCORM2004_GrabAPI();
// This is an example of how to have a property that will be
// exposed be a custom function passing a parameter.
initialize = function(initString) {
return SCORM2004_GrabAPI().Initialize(initString);
};
return {
getApi: grabApi,
init: initialize
}
}());
You can then use this abc object like this throughout your code. Again, this is trying to give an example of how to do what I think you're trying to do based on your comment.
// Assign the SCORM2004_GrabAPI function to a variable.
var SCORM2004_objAPI = abc.getApi();
// Call the Initialize function with an empty string.
abc.init("");
Hmmm… contrary to #krillgar's answer, I believe you were expecting your abc() to return new object. Something like this:
function abc(){
var privateVar;
return {
//multiple variables and functions
a:function(){alert("a")}
}
}
function test(){
var k=abc();
k.a();
}
You should make it an object. In this way you can access its property a.
var abc ={
a:function(){alert("a")}
}
function test(){
var k=abc;//Ofcrse remove the parenthesis
k.a();
}
test();
Related
Background
I want a function keeping track of its own state:
var myObject = {
myFunction: function () {
var myself = this.myFunction;
var firstTime = Boolean(!myself.lastRetry);
if (firstTime) {
myself.lastRetry = Date.now();
return true;
}
// some more code
}
}
The problem with the above code is that the value of this will depend on the site of the function call. I want the function to be able to refer to itself without using:
myObject.myFunction
.bind()
.apply()
.call()
Question
Is it possible to give a function this kind of self awareness independent of its call site and without any help from external references to it?
If you want to store that state on the function instance, give the function a name, and use that name within it:
var myObject = {
myFunction: function theFunctionName() {
// ^^^^^^^^^^^^^^^--------------------- name
var firstTime = Boolean(!theFunctionName.lastRetry);
// ^--------------------------- using it
if (firstTime) {
theFunctionName.lastRetry = Date.now();
// ^------------------------------------------------ using it
return true;
}
// some more code
}
};
You'd do that whenever you want to use a function recursively as well. When you give a name to a function that way (putting the name after function and before (), that name is in-scope within the function's own code. (It's not in-scope for the code containing the function if it's a function expression, but it is if it's a function declaration. Yours is an expression.)
That's a named function expression (where previously you had an anonymous function expression). You may hear warnings about NFEs, but the issues various JavaScript implementations had with them are essentially in the past. (IE8 still handles them incorrectly, though: More in this post on my blog.)
You might consider keeping that state somewhere private, though, via an IIFE:
var myObject = (function(){
var lastRetry = null;
return {
myFunction: function() {
var firstTime = Boolean(!lastRetry);
if (firstTime) {
lastRetry = Date.now();
return true;
}
// some more code
}
};
})();
Now, nothing outside that outer anonymous function can see lastRetry at all. (And you don't have to worry about IE8, if you're supporting stubborn XP users. :-) )
Side note: The unary ! operator always returns a boolean, so your
var firstTime = Boolean(!theFunctionName.lastRetry);
...is exactly equivalent to:
var firstTime = !theFunctionName.lastRetry;
...but with an extra unnecessary function call. (Not that it hurts anything.)
Of course you can, simply give your function an internal named representation and it can refer to itself from there. For example...
var obj = {
doThings:function doThingsInternal(arg1, arg2) {
console.log(arg1, arg2);
for (var arg in doThingsInternal.arguments) {
console.log(arg);
}
}
};
obj.doThings('John', 'Doe');
You could use a simple Closure, if you are not too bent on keeping state existence knowledge within the function. But I guess you don't want that. Another way to do this could be changing the function itself on the first call. Benefits, no/less state variables needed and no costly checks on subsequent calls! -
var myObject = {
myFunction: function () {
// Whatever you wanna do on the first call...
// ...
// And then...
this.myFunction = function(){
// Change the definition to whatever it should do
// in the subsequent calls.
}
// return the first call value.
}
};
You can extend this model to any states by changing the function definition per your state.
I have a function in javascript
var fn = function(){
var obj = {result: true};
return obj.result;
};
I have access to the function, but I need to get the inner obj. Is there a way to do that?
EDIT: Thanks to the answers below, I have managed to come up with a solution.
https://stackoverflow.com/users/1447675/nina-scholz 's answer was the closest, so I marked it as the solution.
var f2 = function fn(){
fn.obj = {result: true};
return fn.obj.result;
};
A client of this function can use it like the following :-
var myFunction = f2;
The function must be called though, to access the inner variables
myFunction();
After that one can do the following.
console.log(myfunction.obj);
This seems to be working. I would, however like to know if this is a good practice.
You cannot access the inner object outside of the scope of the function.
you can access obj when you make it public.
function fn() {
fn.obj = { result: true };
return fn.obj.result;
}
console.log(fn());
console.log(fn.obj.result);
i am generating dynamic javascript in which i create few functions for storing value
function get[dynamicname](){
return "some value";
}
i want to call this method in another function to get the values of all functions i created
i have all the dynamicnames which i used to create the functions in the function which i am calling..
function getallfunctionvals(){
for ( var i = 0; i < array.length; i++ ) {
var s="get";
var ss="()";
console.log(s+array[i]+ss);
}
}
this is how i am calling the dynamically generated functions but in the console i am getting the function name as string not the value inside it
Hi look at This post.
One of the answer:
if you know that its a global function you can use:
var functPtr = window[func_name];
//functPtr()
Otherwise replace window with the parent object containing the function.
if defined function is in gloabal scope, you can use
window[s+array[i]]()
So if you have a function like getName. what it will do it will call something like
window["getName"]();
you can use eval function. Eg.
var s = eval("function get(){}; gat();");
first of all:
function get[dynamicname](){
return "some value";
}
will generate error: SyntaxError: Unexpected token [
Since "[" is not allowed in javascript function name and variable.
But you can do this:
function getName () {console.log('Name')};
function getAge () {console.log('Age')};
When you invoke the above functions, you can do this:
var s="get";
var thingToGet = "Name";
var ss="()";
eval(s + thingToGet + ss)
Did I answer your question?
I have a simple function, I am trying to access the instance variable. But it's giving me some error. How can I access instance variable in Javascript ? I tried below method, but not working
function Test(){
var a=10;
}
var test=new Test();
test.a=20;
For some reason I don't want to go with the following way:
var Test={
a:''
}
You declared a as a variable local to that function, so there is no way to access it outside (as you currently have it)
If you want a to be an instance variable attach it to the object
function Test(){
this.a=10;
}
var test=new Test();
test.a=20;
Change it to this :
function Test(){
this.a=10;
}
Here a good documentation on the subject : Introduction to Object-Oriented JavaScript
Existing answers tell you how to do it by making a a public property. If you really need a private variable, use the following code. The main reason you would use this instead of a public property is to prevent callers from setting a to invalid values.
function Test() {
var a = 10;
this.setA = function(val) {
a = val;
};
this.getA = function(val) {
return a;
};
}
var t = new Test();
t.setA(80);
t.getA(); // 80
I have a javascript getter method like so:
function passTags()
{
var tags = document.getElementById('tags').value;
this.getTag=function()
{
return this.tags;
}
}
How do i call it?
Looks like you've set up a constructor function, so it would be like so
var t = new passTags;
t.getTag();
this.tags is not defined though, so t.getTag() will return undefined. If you meant for it to return the value of tags then change it to
function passTags() {
var tags = document.getElementById('tags').value;
this.getTag = function() {
return tags;
}
}
bear in mind though that the value captured will not update once the constructor function has executed, as this example will demonstrate. One more recommendation would be to use Pascal case for the function name so that it is clear that it is a constructor function.
The way that you have your code set up at the moment though, if it wasn't intended to be a constructor function then you would first have to execute passTags function. This would define a function in global scope, getTag, that could then be executed. This will return undefined however as this.tags is undefined.
You shouldn't define tags as var tags = ... but as this.tags = ...
-- edit
Russ's solution is 'better': tags is now private.