【发布时间】:2014-09-16 11:56:53
【问题描述】:
我的英文写得不好我很抱歉...
我对 var 在函数闭包中的行为有一些疑问,例如:
var c = function(){
var _self = this;
}
当我创建一个新实例时:
var A = new c();
A.logSelf = function(){
console.log(_self);
}
在 A 范围(或闭包...并借助 jQuery 帮助扩展构造函数的默认行为(简单来说):
var c = function(obj){
var _self = this;
this.name = "lol";
this.init = function(){
_self = this;
}
this.sayName = function(){
console.log(_self.name);
}
$.extend(this,obj);
this.init();
}
var A = new c({
name : "A",
init : function(){
_self = this;
},
sayA : function(){
console.log(_self.name)
}
});
现在,如果我在控制台日志 A 中调用 A.sayName() 和 A.sayA(),我会说:“哇,我是有史以来最棒的!”,但是当我试图实例化一个B var all changed:
var B = new c({
name : "B",
init = function(){
_self = this;
}
});
... 现在 A.sayName() 记录 A,但 A.sayA() 记录 B(因为 _self 在所有 c 的实例中现在是我的最后一个实例已创建 [B 在这种情况下])...
为什么?我怎么了?
也许 A 和 B 的闭包是相同的,因为它们都是同一个构造函数的实例?
但是为什么在A和B的c方法ereditend中_self的值是正确的?我不明白这是什么意思!叹息。
工作示例
为什么我需要这个?
在我的 A & B 实例中,我使用了一些 $.ajax 和 jQuery 处理程序,在 jQuery 用来回调的匿名函数中(都知道)this 是对某事的引用,我无法引用该实例包装匿名函数。
每次我需要使用 jQuery 回调或使用 $.ajax 的上下文属性时,我都需要 _self 来轻松引用而无需重估 var _self。
我更喜欢将self 赋值一次,并且在我的实例的范围(或闭包)内它永远不会改变他对this 的引用。
一些例子...
c = function(){
//...
this.render = function() {
//var __self = this;
if (typeof this.view.surce === "undefined") {
//this.writeRequest();
$.ajax({
url: this.config.path + "/index.shtml",
data: this.config.req,
datatype: "html",
success: function(ht) {
__self.view.elements.html = ht;
__self.run();
},
error: function() {
__static.log("Error inside ajax call for view TMPL");
}
})
} else {
this.run();
}
}
//...
this.run = function() {
if (this.view) this.$el = $(__static.tmpl(this.$tmpl.html(), this.view.elements));
this.$el.appendTo(this.$place);
if (typeof this.view.callback === "function") {
this.view.callback.call(this, this.$el);
delete this.view.callback;
}
this.cases();
this.show();
}
//...
}
真正的问题在于A的这个方法:
endpoint : function(){
//var __self = this;
this.$el.find(".call-to").on("click", function(e) {
e.preventDefault();
if(typeof __static.B !== "undefined") return __static.B.show();
//__static is the reference of the scope (all works inside a self invoked anonymous function).
__static.B = new __static.C(Bconfig, __static); //Bconfig is an object that contain all extend and override the C constructor.
__self.close();
__static.B.view = new _viewConf(__static.B.config.type[__self.view.b]);
__static.B.render();
});
},
在这两种情况下,我每次需要使用时都需要与__self竞争。
(我已经在此处搜索了答案,并且通常在 google 中搜索...但我没有找到我的具体案例)
【问题讨论】:
-
如果可以的话,可以发
$.ajax()的回调片段吗? -
我用一些例子更新了我的问题:)
标签: javascript jquery closures this