Calling a variable stored in a literal object

I have this object with literal notation (took out unnecessary 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 tried calling him:

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

None of them worked. How do I access this function?

If I put a function outside the literal notation object, I can call it simply with:

 displayWork(); 
+7
javascript function jquery
source share
3 answers

Like this:

 work.display(); 

The work object display property refers to a function.

Since your function was created using a function expression, the displayWork name can only be used inside the function, so if the function does not need to call itself (recursively), you can refuse this name and just say display : function() { ... } .

+4
source share

The right way:

 work.display(); 

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

0
source share

The right way:
work.display();

But the HTMLworkStart object may not be present if it is not in the global scope. Therefore, you should set it as an argument:

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

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

0
source share

All Articles