Below are "my words", as I understand them. They are by no mean a reference, but my hope is that they can somehow help you understand some key elements of the JavaScript language.
For far more detailed and accurate explanations, refer to Kyle Simpson's series "You don't know JS yet".
- JavaScript is a weakly typed language
- Variables are not declared with a type
- The type of a variable can change when it is assigned
- Every variable has a type
- JavaScript does type coercion
- When comparing two variables of different types, JavaScript converts them to the same type
Demo: http://jsfiddle.net/ntzhrjuu/13/
- Test against falsy values, not just null or undefined
- When needed, use the === and !== operators to check against:
- Value of the variables
- Types of the variables
-If you need to check the type of a variable, use typeof
if(myvar && typeof(myvar) === 'string')
{
// your variable is not falsy and it is a string }
}
JavaScript is an interpreted language
- A script is loaded in a browser and executed
- There is not need to compile it in binary format
JavaScript is compiled
- Each time it is executed, a script is compiled and optimized
JavaScript has two scopes
- Lexical scope: set at authoring time, when you write the script
- Dynamic scope: set at runtime, when the script being executed
The variable this
belongs to the Dynamic scope
- The value of
this
will be determined at runtime - In most cases,
this
will have the value of its function’s call site - Except when constructing an object, where
this
will be the object itself
Demo: https://jsfiddle.net/c6tfxjms/8/
Use lexical capture to prevent binding issues
- Inside the
constructor
, declare a variable and use it instead ofthis
:
var self = this;
self.this.value = 'wow, much string, such value';
this.ShowMyLocation = function () { console.log(self.value) } );
Use explicit binding on existing code that cannot be refactored After the function declaration or when it is passed as a delegate, add the following code (in red):
var bar = new ViewModels.foo();
$("#clickme").click(bar.ShowMyLocation.bind(bar));