代码之家  ›  专栏  ›  技术社区  ›  James Black

如何让匿名函数在事件处理程序中调用时保持其最初的作用域

  •  0
  • James Black  · 技术社区  · 16 年前

    this.plantName .

    undefined .

    .

    TabLinks.prototype.plantName = '';
    
    TabLinks.prototype.init = function() {
        this.updateTab('PlantDropDown', 'retrievePlants', 'retrieveAllPlants', 'tab3', function() { return this.plantName; });
    };
    
    function TabLinks() {
        this.updateTab = function(entityname, wsbyid, webservicename, parentContainer, defaultValue) {
            $("#" + parentContainer + "link").bind('click', function() {
                $.ajax({
                    type: "POST",
    ...
                    success: function(result) {
                        myData = JSON.parse(result.d);
                        $.ajax({
                            type: "POST",
    ...
                            success: function(result2) {
    ...
                                        myelem.value = JHEUtilities.testIsValidObject(defaultValue) ?
                                        defaultValue() :
                                        '';
    

    这是有效的解决方案,我没有意识到函数的两个返回:

    this.updateTab('PlantDropDown', 'retrievePlants', 'retrieveAllPlants', 'tab3',
    function() {
        var app = this;
        return function() {
            return function() {
                return app.plantName;
            }
        }()
    }
    );
    

    defaultValue()();

    1 回复  |  直到 5 年前
        1
  •  0
  •   SingleNegationElimination    16 年前

    function foo(){
        var myFoo = 1;
        return function (){return function() { myFoo += 1; return myFoo }}()
    } //                                                                  ^^