I have noticed something while playing around which has sparked a quick question.
When code is executed in the global/window context, any function declarations get added as methods to the window object.
But when I am in the context of another object, writing a function declaration does not add the method to my objects methods.
function functionInGlobalCtx() { // This will be added as a function to the window object
// code...
}
var myObject = {};
myObject.myObjectFunction = function () {
var $this = this; // The context here is the 'myObject' object
function functionHopefullyInMyObjectCtx() {
// code...
}
}
myObject.myObjectFunction();
Why does the function declaration exist as part of the window object but not the one for the object?
Is this simply 'how JavaScript works' (special rules apply to the global context?) or am I missing something?
Thanks.
All functions declared globally will be attached to the global window object. That's how JavaScript works.
JavaScript only has function scope. So any function declared inside another function is private to the outer function.
The function
functionHopefullyInMyObjectCtxcan not be accessed from outside yet.Declaring a function inside a function does not attach it to the
thisautomatically. However the function remains private and is only accessible within the scope it was declared in.If you wanted to access the
functionHopefullyInMyObjectCtxfunction frommyObject.myObjectFunctionthen here is a way:Here is a good read: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions