0

私はこの記事を読んでいます-http://www.robertsosinski.com/2009/04/28/binding-scope-in​​-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

私の質問は、特にこの行です

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

_function.apply(scope、arguments);が返されるのはなぜですか。そこの?そして、それは何をしていて、何が返されているのでしょうか?私はそのリターンを削除しましたが、それでも機能します。

4

3 に答える 3

1

元の関数 (バインドされている関数) を適用した結果を返します。を作成する_function.applyと、がコンテキストとして_function呼び出されるため、関数内では常に が参照されます。scopethisscope

2 番目のパラメーターargumentsは、すべての引数を元の関数に渡すためにあります。また、returnステートメントは、元の関数呼び出しから返された値がバインドされた関数呼び出しからも返されることを確認するためにあります。

于 2013-01-18T07:42:41.217 に答える
1
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"));

これで、返品が必要な理由がわかります

于 2013-01-18T07:40:57.940 に答える
0

戻り値では、単に新しい関数を返します。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);
  }

_functionfoo、引数scopeです- 。は、関数のすべての引数を含む配列(正確ではない)のようなものです。したがって、:によって、あなたはの最初の引数として提供されるスコープになります。引数を使用する場合は、が含まれます。bindbarargumentsfoo()thisapplyfoo(1,2,3)1,2,3

ログに記録される結果はになりますbaz

于 2013-01-18T07:52:09.197 に答える