this with simple objects

suggest change
var person = {
  name: 'John Doe',
  age: 42,
  gender: 'male',
  bio: function() {
    console.log('My name is ' + this.name);
  }
};
person.bio(); // logs "My name is John Doe"
var bio = person.bio;
bio(); // non-strict: logs "My name is " plus the global object's name

In the above code, person.bio makes use of the context (this). When the function is called as person.bio(), the context gets passed automatically, and so it correctly logs “My name is John Doe”. When assigning the function to a variable though, it loses its context.

In non-strict mode, a bare call uses the global object (window in browsers). window.name is a string, often empty, so the log is not "My name is undefined". In strict mode this is undefined, and this.name throws.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents