我仍然在探索JavaScript中奇怪的部分,我遇到了这个问题。
我知道,在执行上下文的创建阶段,所有变量最初都被设置为未定义的变量,但是函数被全部加载到内存中。所有函数都是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:无法读取未定义属性的“名称”
期望:当两者都是对象时,它们的输出不应该是相同的吗?
发布于 2019-07-10 06:34:05
函数声明是挂起的,但任何涉及赋值( =)的内容都不是。对于解释器,您的第一个代码相当于
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关键字的函数和缺少=的函数)。
https://stackoverflow.com/questions/56964601
复制相似问题