2013-04-09 65 views
2
var x = (arg1, arg2) { 
    this.y = arg1; 
    this.z = arg2; 
} 

x.prototype.a = function() { 
    var self = this; 
    some_obj1.on('data', function() { 
    self.y = 'new y value'; 
    }); 
} 

x.prototype.b = function() { 
    var self = this; 
    some_obj2.on('data', function() { 
    self.z = 'new z value'; 
    }); 
} 

是否有任何方法將自己聲明爲實例變量(顯然不使用'this'),以便它不需要在每個函數中聲明?因此,例如申報「一」是:JavaScript對象原型此參考

x.prototype.a = function() { 
    ob2.on('data', function() { 
    self.z = 'some new value'; 
    }); 
} 

希望這個例子是非常明顯的,這不是測試(問這個問題的時候寫上飛)多的僞代碼,但應該傳達出點。

回答

2

不,你不能。您需要以某種方式修改範圍鏈,以避免使用this。稍微更簡潔的方法是使用Function#bind來指定this

x.prototype.a = function() { 
    ob2.on('data', function() { 
    this.z = 'some new value'; 
    }.bind(this)); 
} 
2

最好的辦法是部分應用參數。以下是較新的Function.prototype.bind的跨瀏覽器實現。 project.bind使用以下實現,如果可用則使用本地Function.prototype.bind;如果本地不可用,則使用自定義實現。

更新 我創建了一個工作Fiddle。現在

project = {}; 
project.bindJs_ = function(fn, selfObj, var_args) { 
    if (!fn) { 
    throw new Error(); 
    } 

    if (arguments.length > 2) { 
    var boundArgs = Array.prototype.slice.call(arguments, 2); 
    return function() { 
     // Prepend the bound arguments to the current arguments. 
     var newArgs = Array.prototype.slice.call(arguments); 
     Array.prototype.unshift.apply(newArgs, boundArgs); 
     return fn.apply(selfObj, newArgs); 
    }; 

    } else { 
    return function() { 
     return fn.apply(selfObj, arguments); 
    }; 
    } 
}; 
// A router for the native Function.prototype.bind 
project.bindNative_ = function(fn, selfObj, var_args) { 
    return /** @type {!Function} */ (fn.call.apply(fn.bind, arguments)); 
}; 



    project.bind = function() { 
     if (Function.prototype.bind && 
      Function.prototype.bind.toString().indexOf('native code') != -1) { 
      project.bind = project.bindNative_; 
     } else { 
      project.bind = project.bindJs_; 
     } 
     return project.bind.apply(null, arguments); 
    }; 

你可以這樣做:

x.prototype.a = function() { 
    ob2.on('data', project.bind(function() { 
    // the this. object inside the function will now point to x. 
    this.z = 'some new value'; 
    }, this, any, argument, you, want, to, pass)); 
} 
+0

您發佈的代碼已損壞... goog來自哪裏? – Dennis 2013-04-09 11:23:29

+0

無法正確選中兩個答案,但這個答案也是正確和有效的。謝謝你的幫助! – gratz 2013-04-10 12:08:30