简体   繁体   中英

How are a javascript object and a javascript function loaded at the creation phase of the execution context?

I'm still exploring the weird parts of JavaScript and I came across this problem.

I know that all the variables are initially set as undefined at the creation phase of the execution context but the functions are loaded in memory in their entirety. And all functions are objects in javascript. So when I'm writing the following code it's not giving a satisfying result.

//Code-1

console.log(fun1.exp);
function fun1(){
    console.log("Hi");
}
fun1.exp = "funnn";



//Code-2

console.log(obj.name);
var obj = {
    "name" : "Albert"
};

Output from Code-1:

undefined

Output from Code-2:

Uncaught TypeError: Cannot read property 'name' of undefined

Expected: When both are objects, shouldn't their outputs be same?

Function declarations are hoisted, but anything that involves assignment (an = ) are not. To the interpreter, your first code is equivalent to

function fun1(){
  console.log("Hi");
}
// END OF HOISTING OF FUNCTION DECLARATIONS

console.log(fun1.exp);
fun1.exp = "funnn";

The fun1.exp line runs after the console.log , so fun1.exp is undefined when logged.

Your second code is equivalent to

// END OF HOISTING OF FUNCTION DECLARATIONS
// (no hoisting at all here, since there are no function declarations)

console.log(obj.name);
var obj = {
  "name" : "Albert"
};

Plain objects are not hoisted; only function declarations (functions which use the function keyword and lack = ) are.

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