Created
July 29, 2015 09:57
-
-
Save Bambina-zz/86af1839f3d82723020b to your computer and use it in GitHub Desktop.
js how does "this" work?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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