Javascript外部范围变量访问

时间:2010-02-16 15:56:41

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

如何在迭代块中访问OperationSelector.selectElement?

1 个答案:

答案 0 :(得分: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")));
    }); 
}