Steve Medley Steve Medley - 5 months ago 8
Javascript Question

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

Answer

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() { ... }.

Comments