如何从嵌套函数引用类变量/方法?
问题描述:
class Foo {
constructor() {
this.foobar = "foobar";
}
bar() {
let _this = this;
return function() {
try {
alert("Attempt 1: "+foobar);//ReferenceError: foobar is not defined
myMethod();
} catch(err) {console.log(err);}
try {
alert("Attempt 2: "+this.foobar);//TypeError: this is undefined
this.myMethod();
} catch(err) {console.log(err);}
try{
alert("Attempt 3: "+_this.foobar);//Works!
_this.myMethod();
} catch(err) {console.log(err);}
}();
}
myMethod() {
alert("myMethod()");
}
}
new Foo().bar();
上面的例子是非常简单的 - 里面bar()
匿名函数是一个jQuery的呼叫最初,但问题的缘故,我没有包括。
为什么不尝试1和2的工作?我是否必须使用_this技巧来引用类变量/方法? 如何从嵌套函数引用类变量/方法?
答
您是否熟悉this
关键字在JavaScript中的工作原理?它的价值取决于函数的调用方式,而不是如何定义。例如,如果你做到以下几点:
var dog = {
greeting:"woof",
talk:function(){
console.log(this.greeting);
}
};
var cat={
greeting:"meow",
talk:dog.talk
};
dog.talk();
cat.talk();
你会看到,当通话功能被称为对象的方法,该对象将被用作this
值。
ES6类也是如此,其中类方法仍然是JavaScript函数,用于决定this
值的规则仍然适用。如果你想避免声明的附配的变量,你应该考虑使用bind
:
var mammal = {
greeting:"<noise>",
getTalk:function(){
return function(){
console.log(this.greeting);
};
},
getTalkBinded:function(){
return (function(){
console.log(this.greeting)
}).bind(this);
}
};
var dog={
greeting:"woof",
talk:mammal.getTalk(),
talkBinded:mammal.getTalkBinded()
};
var cat={
greeting:"meow",
talk:mammal.getTalk(),
talkBinded:mammal.getTalkBinded()
};
dog.talk();
cat.talk();
dog.talkBinded();
cat.talkBinded();
答
您正在返回自执行功能的执行结果和函数执行this
其全球范围内的期间(不你的类对象)。使其工作使用() => {}()
箭头函数调用语法,因为它捕获当前上下文,或function() { }.bind(this)()
。
答
看到这个简单的例子,
function a(){
this.someProp = 5;
console.log(this);
var _this = this; //so we explicitly store the value of `this` to use in a nested function
return function(){
//value of `this` will change inside this function
this.anotherProp = 6;
console.log(this);
//to use the methods and props of original function use `_this`
console.log(_this)
}
}
var c = a.call({}) //prints {someProp: 5}
c.call({}) //prints {anotherProps: 6} {someProp: 5}