2013-07-31 26 views
0

我比任何其他更好奇。它如何將上下文傳遞給函數。它是否將該函數包裝在對象中?我相信,有在JS這樣做沒有jQuery的代理jQuery代理如何工作

function abc(){ 
    console.log(this.name); 
} 
var obj={name:"Something"}; 
$.proxy(abc,obj); 

我怎樣才能做到這一點沒有jQuery的代理一些簡單直接的代碼?

+0

啊,當人們來來往往,並沒有麻煩留下評論 –

回答

4

沒有jQuery的你可以使用bind

var newFunction = abc.bind(obj); 

如果你想與IE8兼容,你可以做

var newFunction = function(){ abc.call(obj) }; 

這裏是jQuery的是如何做的:

// Bind a function to a context, optionally partially applying any 
// arguments. 
proxy: function(fn, context) { 
    var args, proxy, tmp; 

    if (typeof context === "string") { 
     tmp = fn[ context ]; 
     context = fn; 
     fn = tmp; 
    } 

    // Quick check to determine if target is callable, in the spec 
    // this throws a TypeError, but we will just return undefined. 
    if (!jQuery.isFunction(fn)) { 
     return undefined; 
    } 

    // Simulated bind 
    args = core_slice.call(arguments, 2); 
    proxy = function() { 
     return fn.apply(context || this, args.concat(core_slice.call(arguments))); 
    }; 

    // Set the guid of unique handler to the same of original handler, so it can be removed 
    proxy.guid = fn.guid = fn.guid || jQuery.guid++; 

    return proxy; 
},