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

时间:2015-09-11 14:46:24

标签: javascript

如何从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?
        }
    }
}

变体是否最佳:?

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

        return function() {        // nested method
            return innerName;   
        }
    }

3 个答案:

答案 0 :(得分:1)

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

function Foo() {                // class Foo
    var _self = this;

    this.name = 'myName';

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

答案 1 :(得分:1)

像这样:

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?
        }
    }
}

答案 2 :(得分:1)

如果您处于支持ES6的环境中,您还可以arrow functions

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

  this.bar = () = > () => this.name;
}