JS进阶之this指向

1. this指向汇总

this指向:指向其调用者

  1. 简单函数
     function f(){
         console.log(this) //window
     };
     f();
     //因为代码不是运行在严格模式下,this又必须是一个对象,所以他的默认值为全局对象window
     //严格模式下为undefined

  1. 内置函数 this ==== window
     setTimeout(f,1000); //window
  1. 回调函数 —— 简单的理解:一个函数被作为参数传递给另一个函数 this ==== window
     function test(v){
        console.log(v)
    };
    //console.log(test); //整个函数
    //console.log(test('hello')); //调用后的结果

    function f2(callback,v){
        callback(v)
    };
    f2(test,'hello');
    //另一种写法
    f2(function(v){console.log(v)},'hello');  //匿名函数
    //f2(function(v){console.log(this)},'hello'); this ====  window

    var arr = [1,2,3,4,5].filter(function(item,index){
        console.log(this)
    })
  1. 数组 this的指向调用者
    function f3(){
        console.log(this);
    };
    var arr = [f3,4,5,6];
    arr[0]();  //this ====  arr  
    var f = arr[0];  //数组赋值处理后  this指向发生了变化
    f();    //this ==== Window

  1. 对象 obj对象中的方法this === obj
    function f3(){
        console.log(this);
    };
    var obj = {};
    obj.id = 123;
    obj.init = function(){
        console.log(this)  //调用者obj   this === obj
    };
    obj.init()    

    obj.action = f3;   //对象中添加了一个方法  方法赋值f3()
    obj.action();   调用者obj     this === obj
  1. 字面量
    var obj2 = {
        id:1,
        abc:f3
    };
    obj2.abc();  // this === obj2

  1. 构造函数
    function Fun(name,age) {
        this.name = name;
        this.age = age;
        this.action = function(){
            console.log(this)
        }
    };
    var fun2 = new Fun('abc',18);
    fun2.action();  //this 指向的是新创建的对象实例, 而不是构造函数本身

2.如何改变this指向

apply() call() bind()
格式:函数名.call/apply/bind(重新指定的this对象,函数参数,函数参数)
可以将原函数中this的指向修改为新的对象

    var a = 10;
    function f5(x1,x2){
        return this.a + " " +x1 +" "+ x2
    };
    var obj5 = {
        a:100,
        action:f5
    };
    var obj6 ={
        a:9999
    }
    obj5.action(1,2);  //100 1 2
    console.log(obj5.action.call(this,1,2))  //10 1 2   改变作用域
    console.log(obj5.action.apply(window,[1,2])) //10 1 2 
    //obj5.action对象的成员放到window对象上,这样f5的指向就是window
    console.log(obj5.action.apply(obj6,[1,2])) //9999 1 2 

    //bind() 绑定this 也是改变作用域 绑定后不能改变this指向
    var a = 10;
    function f5(x1,x2){
        return this.a + " " +x1 +" "+ x2
    };
    var obj5 = {
        a:100,
        action:f5
    };
    var obj6 ={
        a:9999
    }
    var a8 = f5.bind(obj5,1,2);
    a8(); //100 1 2
    console.log(a8.call(obj6,1,2)) 
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值