简体   繁体   English

调用存储在文字符号对象中的变量

[英]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. work对象的display属性是指函数。

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() { ... } . 因为你的函数是用函数表达式创建的,所以名称displayWork只能在函数中使用,所以如果函数不需要自己调用(递归),你可以选择省略这个名字,然后说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. 由于display是对象的属性,我们可以使用点符号来访问它,并使用()来评估它指向的函数。

The correct way is: 正确的方法是:
work.display();

But the object HTMLworkStart could be missing if it is not in the global scope. 但是,如果对象HTMLworkStart不在全局范围内,则可能会丢失该对象。 So you should set it as argument: 所以你应该把它设置为参数:

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

Then you have to call 然后你必须打电话
work.display(HTMLworkStart);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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