简体   繁体   中英

Calling a variable stored in a literal notation object

I have this literal notation object (took out the irrelevant parts):

var work = {
"display": function displayWork(){
    for(i in work.jobs){
        $('#workExperience').append(HTMLworkStart);

        var formattedEmployer = HTMLworkEmployer.replace('%data%', work.jobs[i].employer);
        var formattedTitle = HTMLworkTitle.replace('%data%', work.jobs[i].title);
        var formattedEmployerTitle = formattedEmployer + formattedTitle;
        var formattedWorkDates = HTMLworkDates.replace('%data%', work.jobs[i].dates);
        var formattedWorkLocation = HTMLworkLocation.replace('%data%', work.jobs[i].location);
        var formattedWorkDescription = HTMLworkDescription.replace('%data%', work.jobs[i].description);

        $('.work-entry:last').append(formattedEmployerTitle);
        $('.work-entry:last').append(formattedWorkDates);
        $('.work-entry:last').append(formattedWorkLocation);
        $('.work-entry:last').append(formattedWorkDescription);
    }
}
};

I have tried calling it with:

work.display.displayWork();
displayWork();
$(work.display).displayWork();

None of these have worked. How do I go about calling this function?

If i place the function outside of the literal notation object than I can call it just fine with:

displayWork();

Like this:

work.display();

The work object's display property refers to the function.

Because your function has been created with a function expression, the name displayWork is only usable from within the function, so if the function doesn't need to call itself (recursively) you could choose to omit this name and just say display : function() { ... } .

The correct way is the following:

work.display();

since the display is a property of the object we could use the dot notation to access it and the () to evaluate the function that it points to.

The correct way is:
work.display();

But the object HTMLworkStart could be missing if it is not in the global scope. So you should set it as argument:

 var work = {
    "display": function (HTMLworkStart){
    ...
    }

Then you have to call
work.display(HTMLworkStart);

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