firstObject
とは両方ともsecondObject
別々のオブジェクトです。キーワードthis
は、その実行コンテキストのオブジェクトを参照します。
<script>
var firstObject = {
says: "something",
test: function() {
//this == firstObject
console.log(this == firstObject); //shows: true
}
}
var secondObject = {
speak: function() {
//this == secondObject
console.log(this.saysToo);
},
saysToo: firstObject.says,
test: function() {
//this == secondObject
console.log(this == secondObject); //shows: true
console.log(this == firstObject); //shows: false
},
}
secondObject.speak();
//this == window
console.log(this===window); //shows: true
console.log(typeof this.saysToo); //shows: undefined
//because "this.saysToo" is same as "window.saysToo" in this (global) context
</script>
関数呼び出しはcall
、apply
メソッドを使用して他のオブジェクトとバインドしthis
、その関数を別のオブジェクトとして動作させることができます。
<script>
var firstObject = {
says: "something",
saysToo: "other"
}
var secondObject = {
speak: function() {
console.log(this.saysToo);
},
saysToo: firstObject.says
}
secondObject.speak(); //shows: "something"
//bind with "firstObject"
secondObject.speak.call(firstObject); //shows: "other"
</script>