【发布时间】:2023-04-08 17:50:02
【问题描述】:
我有以下几点:
var o = {f: function(fn) {
fn.call(o);
}};
var ob = {f: function() {
o.f(function() {
this.x = 2; //HERE: how can this reference ob?
//ob.x = 2;
});
}};
ob.f();
ob.x; // undefined
o.f(fn) 调用 fn,其中 this 绑定到 o。
在这里,我想使用this 访问ob。
但是,当调用ob.f 时,this 将绑定到o。
我认为 JQuery 是这样工作的。
例如:
$(...).blah(function() {
this // this is bound to $(...) jquery object.
...
};
我现在做的是:
var Ob = function() {
var self = this;
self.f = function() {
o.f(function() { self.x = 2; };
};
};
var ob = new Ob();
ob.f();
ob.x; // 2
但出于文体原因,我不喜欢上述内容:
- 使用
new运算符听起来太经典的 OOP。 - 使用
function定义<strong>class</strong> Ob并不直观(至少在开始时是这样)。
这就是为什么我试图用一个对象字面量来定义ob。
但我找不到在函数中引用对象ob 的方法
使用将this 设置为ob 之外的其他对象的方法调用。
我可以执行以下操作:
var ob = {f: function() {
o.f(function() {
self.x = 2;
});
}};
var self = ob;
ob.f();
ob.x;
但我不知道如何考虑以上因素。 我试过了:
function obj(o) {
return function() {
var self = o;
return o;
}();
}
var ob = obj({f: function() {
o.f(function() {
self.x = 2;
});
}});
ob.f();
ob.x;// ReferenceError: self is not defined
那么,有没有办法在对象内部的函数中引用对象
可靠(this 可以根据上下文绑定到任何东西)?
【问题讨论】:
标签: javascript oop this