Javascript outer scope variable access

2020-03-15 06:28发布

问题:

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>');               
    });
}

How could I access OperationSelector.selectElement in iteration block ?

回答1:

Assign it to a local variable in the function scope before your iteration function. Then you can reference it within:

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")));
    }); 
}