简体   繁体   中英

Assigning a function to a variable in JavaScript

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM