const dog = {
bark: function () {
console.log('Woof!');
},
barkTwice: function () {
this.bark();
this.bark();
}
};
dog.bark();
// Woof!
dog.barkTwice();
// Woof!
// Woof!
But what if we just wrote
bark();
instead ofthis.bark();
inbarkTwice
? The function would have first looked for a local variable namedbark
in the scope ofbarkTwice
. Ifbark
isn’t found, it would have looked further up the scope chain.
Is the above statement correct?
What i do not understand about the above statement:
If I call the barktwice method on the dog object in the modified example as seen below, then why does it return a Reference Error, it should find the variable bark, its not in a private scope which is inaccessible by barkTwice.
const dog = {
bark: function () {
console.log('Woof!');
},
barkTwice: function () {
bark();
bark();
}
};
dog.bark();
// Woof!
dog.barkTwice();
// Uncaught ReferenceError: bark is not defined
at Object.barkTwice