[英]How are a javascript object and a javascript function loaded at the creation phase of the execution context?
我仍在探索JavaScript的怪异部分,遇到了这个问题。
我知道在执行上下文的创建阶段,所有变量最初都被设置为undefined,但是这些函数全部都已加载到内存中。 并且所有函数都是javascript中的对象。 因此,当我编写下面的代码时,结果并不令人满意。
//Code-1
console.log(fun1.exp);
function fun1(){
console.log("Hi");
}
fun1.exp = "funnn";
//Code-2
console.log(obj.name);
var obj = {
"name" : "Albert"
};
代码1的输出:
未定义
代码2的输出:
未捕获的TypeError:无法读取未定义的属性“名称”
预期:当两个都是对象时,它们的输出不应该相同吗?
函数声明被吊起,但是任何涉及赋值(an =
)的东西都没有。 对于解释器,您的第一个代码等效于
function fun1(){
console.log("Hi");
}
// END OF HOISTING OF FUNCTION DECLARATIONS
console.log(fun1.exp);
fun1.exp = "funnn";
fun1.exp
行在console.log
之后运行,因此fun1.exp
在登录时undefined
。
您的第二个代码等效于
// 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"
};
没有吊装普通物品; 只有函数声明(使用function
关键字和缺乏=
的function
)才是。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.