2013-01-18 52 views
0

我正在閱讀本文 - http://www.robertsosinski.com/2009/04/28/binding-scope-in-javascript/ - 在其中創建自定義綁定函數。javascript自定義作用域綁定函數

Function.prototype.bind = function(scope) { 
    var _function = this; 

    return function() { 
    return _function.apply(scope, arguments); 
    } 
} 

alice = { 
    name: "alice" 
} 

eve = { 
    talk: function(greeting) { 
    console.log(greeting + ", my name is " + this.name); 
    }.bind(alice) // <- bound to "alice" 
} 

eve.talk("hello"); 
// hello, my name is alice 

我的問題是這條線在particlar

return function() { 
    return _function.apply(scope, arguments); 
    } 

爲什麼在_function.apply(範圍參數)的回報;那裏?它在做什麼和返回什麼? 我刪除了返回,它仍然有效。

回答

2
Why is the return in _function.apply(scope, arguments); there? And what is it doing and what is being returned? I removed that return and it still works. 

如果您想返回一個值,那麼這裏有。目前你的談話功能沒有返回任何值,所以你不需要它。如果你改變你的談話功能

eve = { 
    talk: function(greeting) { 
    return (greeting + ", my name is " + this.name) ; 
    }.bind(alice) // <- bound to "alice" 
} 

console.log(eve.talk("hello")); 

現在,你會明白爲什麼需要回報

1

它返回應用原函數的結果(一個被綁定)。當您製作_function.apply時,將以scope作爲上下文調用_function,因此函數this內將始終引用scope

第二個參數arguments用於將所有參數傳遞給原始函數。並且return語句用於確保從原始函數調用返回的值也將從綁定函數調用返回。

1

在返回中,您只需返回新函數。您在返回的匿名函數的範圍內關閉scope_function。它被稱爲閉包 - 在父函數中可見的所有變量(返回匿名函數的變量)在返回的函數中都是可見的。

這裏就是你們的榜樣:

Function.prototype.bind = function(scope) { 
    var _function = this; 

    return function() { 
    return _function.apply(scope, arguments); 
    } 
}; 

function foo() { 
    console.log(this.foobar); 
} 

var bar = { 
    foobar: 'baz' 
}; 

foo = foo.bind(bar); 

所以,現在一步一步:foo.bind(bar);返回功能:

function() { 
    return _function.apply(scope, arguments); 
    } 

_functionfooscopebind說法 - bararguments就像是一個數組(不完全),它包含一個函數的所有參數,所以通過:foo(),您的this將作爲apply的第一個參數提供的作用域。如果使用foo(1,2,3)參數將包含1,2,3

記錄結果爲baz