- It's where to look for things.
- Javascript has function scope only.
- There are 2 predominant modules:
- Lexical scope: building example - goes up one level looking for there. The top of the building is the global scope
- Dynamic scope:
this
example. Moves to any level of the building as if it were looking for an address.
- Cheating scope:
eval
andwith
(bad mechanisms, avoid it).
var foo = "foo";
(function(){
var foo = "foo2";
console.log(foo); // "foo2"
})();
console.log(foo); // "foo"
var foo = "foo";
(function(bar){
var foo = bar
console.log(foo); // "foo"
})(foo);
console.log(foo); // "foo"
Every function while executing, has a reference to its current execution context, called this.
There are 4 rules for how the this
keyword gets bound and they all depend on the call side (place in code where a function gets executed ()
) in order of precedence from higher they are:
new
keyword- Explicit binding (
call
,apply
orbind
) - Implicit binding (owning or containing object
o2.foo()
) - Default rule (
foo()
)
- Brand new object gets created
- Object gets linked
- The context it set to the this
- It returns
this
- The
.bind
utility - Why do that? hard binding, if you want to be predictable, you always want your methods to go to a particular object
- Tradeoff is the flexibility
- If you find yourself using
bind
all the time think about why you're even usingthis
.
- Using the
new
keyword.
- Is when a function remembers and accesses its lexical scope even when that function is executed ouside of its lexical scope
- It's created when an inner function is transported outside of the outer function.
- Has to be an outer functions, return one or more inner functions that are closure of the scope.
- Benefitial for hiding stuff, not exposing inner details.
function foo(){
var bar = "bar";
return function() {
console.log(bar);
};
}
function bam(){
foo()(); // "bar"
}
bam();
function foo(){
var bar = "bar";
setTimeout(function() {
console.log(bar);
}, 1000);
}
foo();
function foo(){
var bar = "bar";
$("#btn").click(function(evt){
console.log(bar);
});
}
foo();
var foo = (function(){
var o = { bar : "bar" };
return {
bar: function(){
console.log(o.bar);
}
};
})();
foo.bar();
var foo = (function(){
var publicAPI = {
bar: function(){
publicAPI.baz();
},
baz: function(){
console.log("baz");
}
};
return publicAPI;
})();
foo.bar();
define("foo", function(){
var o = { bar: "bar" };
return {
bar: function(){
console.log(o.bar);
}
};
});
- Every single "object" is built by a contructor function
- A constructor makes an object linked to its own prototype