javascript自定义范围绑定函数
我正在阅读这篇文章--其中创建了一个自定义绑定函数javascript自定义范围绑定函数,javascript,scope,bind,Javascript,Scope,Bind,我正在阅读这篇文章--其中创建了一个自定义绑定函数 Function.prototype.bind = function(scope) { var _function = this; return function() { return _function.apply(scope, arguments); } } alice = { name: "alice" } eve = { talk: function(greeting) { console.lo
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
为什么返回在_函数中。应用(范围、参数);那里它在做什么?它在归还什么?
我删除了这个返回,它仍然有效
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.
如果您想返回一个值,就可以使用此选项。目前您的talk函数没有返回任何值,因此您不需要它。如果您将通话功能更改为
eve = {
talk: function(greeting) {
return ( greeting + ", my name is " + this.name) ;
}.bind(alice) // <- bound to "alice"
}
console.log(eve.talk("hello"));
eve={
谈话:功能(问候语){
return(greeting+,我的名字是“+this.name”);
}.bind(alice)/返回应用原始函数(被绑定的函数)的结果。当您创建\u函数.apply
时,\u函数
将以作用域
作为上下文调用,因此在函数中,此
将始终引用作用域
第二个参数arguments
用于将所有参数传递给原始函数。而return
语句用于确保从原始函数调用返回的值也将从绑定函数调用返回。在返回中,您只需返回新函数。关闭scope
和\u函数
在返回的匿名函数的作用域中。它称为闭包-父函数中可见的所有变量(返回匿名函数的变量)在返回的函数中可见
以下是您的示例:
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);
}
\u函数
是foo
,范围
是绑定
参数-条
参数
类似于包含函数所有参数的数组(不完全是),因此by:foo()
,您的此
将作为apply
的第一个参数提供。如果您使用foo(1,2,3)
参数将包含1,2,3
记录的结果将是baz
function() {
return _function.apply(scope, arguments);
}