Let’s first understand, local scope and global scope
var numb = 5;
function test1() {
console.log(numb); // 5 局部作用域可以访问全局作用域
}
test1();
console.log(numb); //5
var numb = 5;
console.log(str) //str is not defined 全局访问不到局部作用域
function test1() {
console.log(numb);
var str='这是文字'
}
test1();
console.log(str) //str is not defined
· Local scope hoisting variable declarations
var numb = 5;
function test1() {
console.log(numb); //unde 局部作用域的变量声明提升
var numb = '100';
console.log(numb); //100 //局部赋值
}
test1();
console.log(numb); //5 //全局变量
The if statement has no scope
console.log(str); //undefined 此时提升,没有进入判断
if (true) {
var str = "文字";
}
console.log(str); //文字
console.log(str); //undefined 此时提升,没有进入判断
if (false) {
var str = "文字";
}
console.log(str); //undefined 此时提升,没有进入判断
` for loop is the same
console.log(i) //undefined 定义了,没有开始循环
console.log(str)//undefined 定义了,没有开始循环
for(var i=0;i<5;i++){
var str='文字'
}
console.log(i,'--for之后')//5 循环结束赋值
console.log(str,'--for之后')//文字 循环结束赋值
var num=1;
function test(){
//此时的局部num不受到if影响,声明提升为undefined 。然后不进入if
if(false){
var num=2
}
console.log(num) //undefiend
}
test()
Let's take a look at a classic topic
function Foo(){
getName = function(){
console.log(1);
};
return this;
}
Foo.getName = function(){
console.log(2);
}
Foo.prototype.getName = function(){
console.log(3);
}
var getName = function(){
console.log(4);
}
function getName(){
console.log(5);
}
Foo.getName();//2 静态属性
getName();//4 函数变量申明提升,随后被表达式覆盖,5--4
Foo().getName();//1 调用foo()的getName()方法,同时把局部的getName()替换了window下的
getName();//1 此时访问的window,也就是上一步的局部的getName()
new Foo.getName()//2 Foo.getName-静态属性返回2 ,new 只是创建了一个实例
new Foo().getName();//3 先执行(new Foo())创建了一个实例,然后去找getName()方法,没有就去原型上找
new new Foo().getName();//3
{{o.name}}
{{m.name}}