A super condensed JavaScript reference for Watch and Code students.
- Most of your time will be spent reading, not writing.
- Simulates working at a company or open source project.
- It's the fastest way to learn and improve.
- Learn how to ignore large parts of a codebase and get a piece-by-piece understanding.
- Read the docs (if they exist).
- Run the code.
- Play with the code to see how it behaves.
- Think about how the code might be implemented.
- Get the code into an editor so that you can modify it.
- Look at the file structure.
- Get a sense for the vocabulary.
- Keep a note of unfamiliar concepts that you'll need to research later.
- Do a quick read-through without diving into concepts from #3.
- Test one feature with the debugger.
- Document and add comments to confusing areas.
- Research items in #3 only if required.
- Repeat.
- Replicate parts of the app by hand (in the console).
- Make small changes and see what happens.
- Add a new feature.
function logThis() {
console.log(this);
}
logThis(); // window
var myObject = {
myMethod: function() {
console.log(this);
}
};
myObject.myMethod(); // myObject
// However, for functions that are called inside of myObject.myMethod
// (like anotherFunction), `this` will revert to the default case.
function anotherFunction() {
console.log(this);
}
var anotherObject = {
anotherMethod: function() {
anotherFunction();
}
};
anotherObject.anotherMethod(); // window
Case 3: In a callback function, assume the default case unless the outer function explicitly sets this
on the callback function.
function outerFunction(callback) {
callback();
}
outerFunction(function() {
console.log(this); // window
});
Case 4: In a function that's being called as a constructor, this
points to the object that the constructor is creating.
function Person(name) {
this.name = name;
}
var gordon = new Person('gordon');
console.log(gordon); // {name: 'gordon'}
Case 5: When you explicitly set the value of this
manually using bind
, apply
, or call
, it's all up to you.
function logThis() {
console.log(this);
}
var explicitlySetLogThis = logThis.bind({name: 'Gordon'});
explicitlySetLogThis(); // {name: 'Gordon'}