Why does calling click()
here prints out the value
property.
class Button {
constructor(value) {
this.value = value;
}
click = () => {
return this.value;
}
}
let button = new Button("hi")
console.log(button.click()) //hi
And calling click
here prints the value property.
function Button2(value){
this.value = value
this.click = () => {
return this.value
}
}
let button2 = new Button2("hi")
console.log(button2.click()) //hi
However, calling click()
here prints undefined. This is what I would expect to happen for both examples, since arrow functions have no this
.
let button2 = {
value:"hi",
click: () => { return this.value }
}
console.log(button2.click()) //undefined
When printing all 3 objects in devtools, they look identical.
button, button2, and button3 when logged in devtools:
{value: "hi", click: ƒ}
click: () => { return this.value }
value: "hi"
__proto__: Object
Why does the first 2 examples print hi
but the third prints undefined
, even though the objects look the same when printed?