Javascript外部范围变量访问

dmi*_*aev 8 javascript scope

OperationSelector = function(selectElement) {
    this.selectElement = selectElement;
}

OperationSelector.prototype.populateSelectWithData = function(xmlData) {
    $(xmlData).find('operation').each(function() {
        var operation = $(this);
        selectElement.append('<option>' + operation.attr("title") + '</option>');               
    });
}
Run Code Online (Sandbox Code Playgroud)

我怎么能在迭代块中访问OperationSelector.selectElement?

And*_*y E 13

在迭代函数之前将其分配给函数作用域中的局部变量.然后你可以在其中引用它:

OperationSelector = function(selectElement) { 
    this.selectElement = selectElement; 
} 

OperationSelector.prototype.populateSelectWithData = function(xmlData) { 
    var os = this;
    $(xmlData).find('operation').each(function() { 
        var operation = $(this); 
        os.selectElement.append(new Option(operation.attr("title")));
    }); 
}
Run Code Online (Sandbox Code Playgroud)