this的指向

一、this的指向

1.谁调用该函数this的指向就指向谁
2.回调函数中的this的指向永远指向window
3.this指向当前的作用域,即离他最近的大括号
4.箭头函数的this的指向会指向离自己最近的作用域
5.构造函数中的this指向实例化对象
6.箭头函数本身是没有this的指向
7.在严格模式下,普通函数或匿名函数的this指向undefined,但是定时器和箭头函数中的this还是指向window(在严格模式下,箭头函数中的this还是会指向离自己最近的作用域)。如果将严格模式去掉,则普通函数、匿名函数、定时器、箭头函数的this都指向window

例子:

1)setTimeout(function(){
    console.log(this);//window调用的这个函数,所以this指向window    
},0)
2)document.onclick = function(){
    console.log(this);//指向window
}
3)function fn(){
    console.log(this);
}
document.onclick = function(){
    fn();//其中的this指向window,因为是window调用的fn()
}
4)var obj = {
    name:"123",
    age:19,
    show(){
        console.log(this);//指向obj,因为是obj调用的show()
    }
}
obj.show();
5)var obj = {
    name:"123",
    age:19,
    show(){
        (function(){
            console.log(this);//this指向window,因为this指向离他最近的作用域,即大括号,是window调用了function这个函数,所以this指向window
        })()
    }
}
6)var obj = {
    name:"123",
    show(){
        var fn = ()=>{
            console.log(this);//this指向obj。箭头函数的this的指向会指向离自己最近的作用域,即show()函数,而show()函数是obj调用的,所以this指向obj
        }
        fn();
    }
}
obj.show();
7)class Person{
    constructor1(name){
        this.name = name;
    }
    show(){
        console.log(this);
    }
}
var p = new Person("张三");
p.show();//this指向实例化的对象
8)"use strict"
var fn = function(){
    console.log(this);//this指向undefined,因为在严格模式下,普通函数的this不再指向window,而是指向undefined
}
fn();
9)"use strict"
setTimeout(function(){
    console.log(this);//this指向window,因为在严格模式下,定时器是个例外,其中的this还是会指向window
},0)
10)"use strict"
var fn = ()=>{
    console.log(this);//指向window。因为在严格模式下,箭头函数中的this还是会指向离自己最近的作用域,即fn,而fn是window调用的。
}
fn();

二、当new操作符执行时js会执行哪些操作

1.开辟内容空间
2.将this的指向指向当前内容空间

三、箭头函数

1.箭头函数是没有arguments的,因此在es6中运用的是扩展运算符(...就是扩展运算符)
2.普通函数this的指向指向调用自己的那个对象,在严格模式中this的指向不再指向window,而是undefined(除了定时器和箭头函数还会指向window外)
3.箭头函数的基本使用:

1)如果形参只有一个,其返回值的代码只有一行,则不需要加{},也不需要加return :
var fn = x => x + 100;//作用是返回一个值
console.log(fn(2));//则会返回一个102
2)如果返回值是一个对象,则用()包起来:
var fn = x => ({
    name:"张三",
    age:x
})
console.log(fn(20));//则返回{name:"张三",age:20}

 

posted @ 2019-03-16 20:18  leslie-cheung  阅读(100)  评论(0编辑  收藏  举报