我有以下内容:
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
绑定(bind)到 o。
在 HERE,我想使用 this
访问ob。
然而,当ob.f
被称为,this
绑定(bind)到 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。 - 定义
<strong>class</strong> Ob
使用function
不直观(至少在开始时)。
这就是我尝试定义 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
可以根据上下文绑定(bind)到任何东西)?
最佳答案
在 JavaScript 中,函数是对象,有两种调用函数的方法:
call(scope, arg1, arg2, ...);
apply(scope, args); // args is an array of arguments to call the function with
第一个参数“scope”是函数内绑定(bind)到“this”的对象。所以,下面的例子是等价的:
obj.method(1, 2, 3);
obj.method.call(obj, 1, 2, 3);
obj.method.apply(obj, [1, 2, 3]);
在您的第一个示例中,您使用“o”作为范围调用传递给 o.f() 的函数:
var o = {f: function(fn) {
fn.call(o);
}};
因此你传入的函数 'ob' 引用 'o' 是这样的:
var ob = {f: function() {
o.f(function() {
this.x = 2; //HERE: how can this reference ob?
//ob.x = 2;
});
}};
在“HERE”这一行中,“this”实际上是“o”。
您可以尝试以下方法:
var ob = {f: function() {
var self = this;
o.f(function() {
self.x = 2; // self is ob now
});
}};
或者您可以修改函数“o.f”以获取范围参数:
var o = {f: function(fn, scope) {
fn.call(scope || this); // Uses the given scope or this (= 'o') if no scope is provided
}};
然后你可以在'ob'中传递'this':
var ob = {f: function() {
o.f(function() {
this.x = 2; // 'this' will be the 'outer' this
}, this); // Here: this as scope
}};
关于javascript - 如何在其成员函数之一中引用对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/569654/