I am trying to understand execution contexts, creation phase, and execution phase.
I was wondering, could someone please help me to understand why,
console.log(thisFunction.ojbect1);
Returns - 'undefined'.
I would have thought that, after the creation phase, when the variables are assigned 'undefined', the execution phase is run, where the variable, is then filled with the object.
So why do I get the 'undefined' for 'object1', and not the whole object?
Many thanks. Code below.
var thisFunction = function(){
var object1 = {
firstname: 'Mark',
printName: function(){
console.log(this.firstname);
}
};
object1.printName();
};
thisFunction();
console.log(thisFunction.object1);
"Object1" is not a property of "thisFunction", that is why you can not call it. "Object1" is a variable created inside the scope of "thisFunction".
You can only reach variables of parent scopes.
Here are some interesting reads if you want to know more about function scopes.
This works as you except:
var thisFunction = function(){
this.object1 = {
firstname: 'Mark',
printName: function(){
console.log(this.firstname);
}
};
this.object1.printName();
};
var tf = new thisFunction();
console.log(tf.object1);
Using typeof
helps you better understand the difference between object and function:
console.log(typeof thisFunction);
console.log(typeof tf);
console.log(typeof tf.object1);
console.log(typeof tf.object1.firstname);
Output:
function
object
object
string
See this example in Plunker
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.