Skip to content

Instantly share code, notes, and snippets.

@Bambina-zz
Created July 29, 2015 09:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Bambina-zz/86af1839f3d82723020b to your computer and use it in GitHub Desktop.
Save Bambina-zz/86af1839f3d82723020b to your computer and use it in GitHub Desktop.
js how does "this" work?
var sharedFuncSayName = function(){
console.log("Name is " + this.name);
}
var alice = {
name: "Alice",
sayName: sharedFuncSayName
}
var brian = {
name: "Brian",
sayName: sharedFuncSayName
}
alice.sayName(); //=>Name is Alice sayNameプロパティを持つ変数aliceがthisに入っている。
brian.sayName(); //=>Name is Brian sayNameプロパティを持つ変数aliceがthisに入っている。
//関数呼び出しの際にthisを指定するにときは、call関数を使用する。
//call関数の第一引数に指定したオブジェクトがthisにセットされる。
//第二引数以降は元の関数の引数として渡される。
sharedFuncSayName.call(alice); //=>Name is Alice
sharedFuncSayName.call(brian); //=>Name is Brian
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment