this depends on how a function is called, not where it is written. Lose it by taking the method out of its object, then fix it with bind.
JavaScript · beginner · 7 min · 12 steps · free
const timer = {
name: 'tea',
seconds: 3,
describe() {
return `${this.name}: ${this.seconds}s`;
},
};
console.log(timer.describe());
const detached = timer.describe;
try {
detached();
} catch (err) {
console.log('lost this:', err.message);
}
const bound = timer.describe.bind(timer);
console.log(bound());timer is created and points to a new Object: {name: "tea", seconds: 3, describe: function describe()}.timer.describe(): the object before the dot is timer, so this = timer.describe returns "tea: 3s".describe() has finished, so its variables are gone. It prints tea: 3s.detached gets the same function, but taken out of the object.detached() is called with nothing before the dot, so this is undefined.err holding the error.lost this: Cannot read properties of undefined (reading 'name').bind(timer) makes a new function whose this is always timer.describe(). It gets its own variables.describe returns "tea: 3s".Answer: undefined
Answer: obj
← Classes and Inheritance · Map and Set →