Skip to content

Instantly share code, notes, and snippets.

@murayama
Created July 9, 2013 01:48
Show Gist options
  • Save murayama/5954027 to your computer and use it in GitHub Desktop.
Save murayama/5954027 to your computer and use it in GitHub Desktop.
javascriptのbind関数の使い方

javascriptのbindの使い方

function Parson (name) {
  this.name = name;
}

Parson.prototype.say = function () {
  console.log(this.name);
};

というコードがあった場合

var parson = new Parson('smith');
parson.say();

smith

という結果が得られる
ただし、

setTimeout(parson.say, 10);

のようにするとthisが解決できずにundefinedになってしまう
この時にbindを活用する

setTimeout(parson.say.bind(parson), 10);

bindでオブジェクトを渡してあげるとthisを束縛できる

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment