简体   繁体   中英

Why when I do a console.log is my object within a function returned as 'undefined'? (Learning about creation phase, execution phase)

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.

  1. You need to use this to assign a variable to function-object thisFunction .
  2. Then you need to use new to create an object of thisFunction .

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM