`this` is a "free" contextual reference that every function gets.
What it references depends on how the function is invoked.
When used in a regular function call, `this` refers to the global object (window).
When used in a constructor, `this` refers to the newly created object.
It's just an ordinary object, so you can add what ever you like to it.
You don't even need the `return` statement.
In fact, the `return` statement is ignored.
Unless you return an object.
No, it's not just you, it's weird.
Oops! I forgot to invoke that constructor with `new`
- Everyone at some point
It is never a good idea to put new directly in front of function
-Douglas Crockford (http://yuiblog.com/blog/2006/11/13/javascript-we-hardly-new-ya/)
WARNING: Highly Controversial!
Opinions may vary... but they're wrong.
When used in a method on an object, `this` refers to the host object (the thing that comes before the dot).
`this` is almost entirely unnecessary.
var o = (function () {
var firstName = "Cory",
lastName = "Brown";
return Object.create(null, {
firstName: {
get: () => firstName,
set: (fn) => firstName = fn
},
lastName: {
get: () => lastName,
set: (ln) => lastName = ln
},
fullName: {
get: () => firstName + ' ' + lastName
}
});
})();
var o = (function () {
var firstName = "Cory",
lastName = "Brown";
return Object.create(null, {
firstName: {
get: () => firstName,
set: (fn) => firstName = fn
},
lastName: {
get: () => lastName,
set: (ln) => lastName = ln
},
fullName: {
get: () => firstName + ' ' + lastName
}
});
})();