2009-02-20 48 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); 
相關問題