[英]How to accede to the variable from the nested function in 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;
}
}
更常见的方法是保留对整个外部对象的引用:
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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.