const user1 = {
name: 'Sherlock Holmes',
address:{
street:'Baker street',
number:"221B",
},
sayMyAddress:function (){
console.log(`My address is ${this.address}`)
console.log(this.address)
}
}
user1.sayMyAddress()
The result:
My address is [object Object]
{ street: 'Baker street', number: '221B' }
Why the this keyword shows the address value in the second case and doesn't in the first? the scope in this case isn't in the object user?
The result of the conversion of the address to a string is '[object Object]' as we'd expect. For example, if you do
console.log({}.toString())
you'll get an output of:
[object Object]
A small change in the code will give the desired result:
const user1 = {
name: 'Sherlock Holmes',
address: {
street: 'Baker street',
number: "221B",
},
sayMyAddress: function() {
console.log(`My address is ${this.address.number} ${this.address.street}`)
}
}
user1.sayMyAddress()
.as-console-wrapper { max-height: 100% !important; }
You could also add a toString() function on the address object:
const user1 = {
name: 'Sherlock Holmes',
address: {
street: 'Baker street',
number: "221B",
toString() { return `${this.number} ${this.street}` }
},
sayMyAddress: function() {
console.log(`My address is ${this.address}`)
}
}
user1.sayMyAddress()
.as-console-wrapper { max-height: 100% !important; }
this.address is an object, so even if the console.log is sympatic enough to output the full object with values if you pass it the object directly, if you use it in a string you'll get [object Object].
Just try it like this
console.log(`My address is ${this.address.street} ${this.address.number}`)
You are trying to log the object itself. So the output result is pretty much expected.
Change the log line from:
console.log(`My address is ${this.address}`)
to:
console.log(`My address is ${this.address.street} ${this.address.number}`)