如何从JavaScript的嵌套函数中加入变量

How to accede to the variable from the nested function in JavaScript?

本文关键字:变量 函数 嵌套 JavaScript      更新时间:2023-09-26

如何加入JavaScript中嵌套函数的变量?

function Foo() {                // class Foo
    this.name = 'myName';
    this.bar = function() {     // 'bar' method
        return function() {     // nested method
            return this.name;   // how to accede to that?
        }
    }
}

变量bellow是最优的吗?

    this.bar = function() {        // 'bar' method
        var innerName = this.name; // duplicated variable :-/
        return function() {        // nested method
            return innerName;   
        }
    }

更常见的方法是保持对整个外部对象的引用:

function Foo() {                // class Foo
    var _self = this;
    this.name = 'myName';
    this.bar = function() {     // 'bar' method
        return function() {     // nested method
            return _self.name;   
        }
    }
}

像这样:

function Foo() {                // class Foo
    var that = this;
    this.name = 'myName';
    this.bar = function() {     // 'bar' method
        return function() {     // nested method
            return that.name;   // how to accede to that?
        }
    }
}

如果你在支持ES6的环境中,你也可以使用箭头函数:

function Foo() {
  this.name = 'myName';
  this.bar = () = > () => this.name;
}