Sam*_*Sam 61 javascript jquery scope class parent
我在javascript中的普通类中有一个jquery类.是否可以从jquery类中的回调函数访问父类范围内的变量?
我的意思的一个简单示例如下所示
var simpleClass = function () {
this.status = "pending";
this.target = jqueryObject;
this.updateStatus = function() {
this.target.fadeOut("fast",function () {
this.status = "complete"; //this needs to update the parent class
});
};
};
Run Code Online (Sandbox Code Playgroud)
现在在上面的示例中,回调函数尝试访问jquery对象的范围.有没有办法访问父类中的状态变量?
Tom*_*ers 99
您将"this"设置为父函数中的变量,然后在内部函数中使用它.
var simpleClass = function () {
this.status = "pending";
this.target = jqueryObject;
var parent = this;
this.updateStatus = function() {
this.jqueryObject.fadeOut("fast",function () {
parent.status = "complete"; //this needs to update the parent class
});
};
};
Run Code Online (Sandbox Code Playgroud)
ins*_*ns0 35
无论如何,我会将这个问题的答案发布到这个旧问题,因为之前还没有人发布过这个问
您可以bind在函数调用上使用该方法来定义this属于的范围 .
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind
每次创建方法时都是Normaly - this属于函数的当前范围.scope2中的变量无法查看scope1中的变量.
例如
function(){
// scope 1
this.baz = 'foo';
function(){
// scope 2
this.baz // not defined
};
};
Run Code Online (Sandbox Code Playgroud)
使用该bind方法,您可以从this函数内部定义范围.所以使用 .bind(this)你告诉被调用函数他们自己的范围来自this父函数的范围,如:
function(){
// scope 1
this.baz = 'foo';
function(){
// scope 1
this.baz // foo
}.bind(this);
};
Run Code Online (Sandbox Code Playgroud)
所以在你的情况下,这将是使用该bind方法的一个例子
var simpleClass = function () {
this.status = "pending";
this.target = jqueryObject;
this.updateStatus = function() {
this.target.fadeOut("fast",function () {
this.status = "complete"; //this needs to update the parent class
}.bind(this));
}.bind(this);
};
Run Code Online (Sandbox Code Playgroud)
使用箭头功能
箭头函数没有它自己的
this。使用this封闭词法范围的值;箭头函数遵循正常的变量查找规则。因此,在搜索this当前范围中不存在的内容时,最终会this从其包围范围中找到它们。
普通函数语法
function(param1, param2) {}
箭头函数语法
(param1, param2) => {}
用法
const simpleClass = function () {
this.status = "pending";
this.target = jqueryObject;
this.updateStatus = function() {
this.target.fadeOut("fast", () => { // notice the syntax here
this.status = "complete"; // no change required here
});
};
};
Run Code Online (Sandbox Code Playgroud)
在ECMAScript 2015类中使用Arrow函数
class simpleClass {
constructor() {
this.status = 'pending';
this.target = jqueryObject;
}
updateStatus() {
this.target.faceOut('fast', () => {
this.status = "complete";
});
}
}
const s = new simpleClass();
s.updateStatus();
Run Code Online (Sandbox Code Playgroud)
描述的代码仅在现代浏览器中有效。