2009-02-20 49 views
1

我有以下几点:如何在一个成员函数中引用一个对象?

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势必邻。

在这里,我想用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 

但我不喜欢上面的格式上的原因:

  1. 使用new操作听起来太古典OOP。
  2. 使用function定义class 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可以绑定到任何东西)?

回答

1

遵循道格拉斯克罗克福斯简单的构造函数模式,我会做一个使用对象字面值而不是新值的构造函数函数。像这样:

var o = {f: function(fn) { 
    fn.call(o); 
}}; 

function obj() { 
    var me = {}; 
    me.f = function() { 
     o.f(function() { 
      me.x = 2; 
     }); 
    }; 
    return me; 
} 

var ob = obj(); 
ob.f(); 
ob.x; // 2 
+0

太棒了!就是我想要的! – numeric 2009-02-20 14:26:14

+0

'self'已经是一个全局变量,比如'undefined'和'NaN'。请用另一个名字来减少混淆。 – some 2009-02-20 14:59:55

3

在JavaScript中,函数是对象,其具有两个方法来调用函数:

call(scope, arg1, arg2, ...); 
apply(scope, args); // args is an array of arguments to call the function with 

第一个参数,“范围”,被绑定到“这个”的对象在功能范围内。因此,以下示例是等效的:

obj.method(1, 2, 3); 
obj.method.call(obj, 1, 2, 3); 
obj.method.apply(obj, [1, 2, 3]); 

在第一个示例中,您正在调用传递给o的函数。f()的使用 'O' 为范围:

var o = {f: function(fn) { 
    fn.call(o); 
}}; 

因此你的函数在 '作业' 的引用的 'o' 通过作为这样的:

var ob = {f: function() { 
    o.f(function() { 
     this.x = 2; //HERE: how can this reference ob? 
     //ob.x = 2; 
    }); 
}}; 

在线 '这里', '这个' 是实际上是'o'。

你可以尝试以下方法:

var ob = {f: function() { 
    var self = this; 
    o.f(function() { 
     self.x = 2; // self is ob now 
    }); 
}}; 

或者你可以修改“的”功能采取了范围参数:

var o = {f: function(fn, scope) { 
    fn.call(scope || this); // Uses the given scope or this (= 'o') if no scope is provided 
}}; 

那么你可以传递“这个”在“OB” :

var ob = {f: function() { 
    o.f(function() { 
     this.x = 2; // 'this' will be the 'outer' this 
    }, this); // Here: this as scope 
}}; 
0

你可以不用辅助功能,只是用文字:

var o = {f: function(fn) { 
    fn.call(o); 
}}; 
var ob = {f: function() { 
    var self = this; // this == ob 
    o.f(function() { 
     self.x = 2; // self == enclosing function's this == ob 
    }); 
}}; 
ob.f(); 
assert(ob.x == 2); 
相关问题