thisは今のスコープのオブジェクト自体を指します
// A:
obj = {
name: "松田信介",
hello: function () {
console.log(name)
}
}
console.log(obj.name)
// B:
obj = {
**name: "松田信介",**
hello: function () {
console.log(this.name)
}
}
省略記法もあります
obj = {
**name: "松田信介",**
hello () {
console.log(this.name + "さん、こんにちは")
},
goodbye () {
console.log(this.name + "さん、こんばんは")
}
}
オブエジェクトの中にいない場合は、globalにいる・・・??
var hoge = "hogehoge"
console.log(hoge)
// "hogehoge"
console.log(this.hoge)
// "hogehoge"
console.log(window.hoge)
// "hogehoge"
this === globalThis // true
this === window // true
this
がないとグローバル変数を参照してしまう
var obj = {
name: "松田",
birthday: "1985/04/13",
hello: function(){
console.log(name + birthday)
// console.log(this.name + " " + this.birthday)
}
}
var obj = {
name: "松田",
birthday: "1985/04/13",
hello: function(){
console.log(this.name + " " + this.birthday)
},
** IntervalHello: function(){
window.setInterval(this.hello, 1000)
}
}
var obj = {
name: "松田",
birthday: "1985/04/13",
hello: function(){
console.log(this.name + " " + this.birthday)
},
IntervalHello: function(){
window.setInterval(() => { this.hello() }, 1000)
}
}