美文网首页
this apply call bind

this apply call bind

作者: SailingBytes | 来源:发表于2019-01-04 16:48 被阅读0次

怎么改变 this 的指向

1、使用 ES6 的箭头函数

2、在函数内部使用 _this = this

3、使用 apply、call、bind

4、new 实例化一个对象

5、闭包

var a = 'window_a';

var objFun = {

    a: 'local_a',

    fun1: function () { console.log(this.a) }, 

    fun2: function () {

        setTimeout( function() => { this.fun1(); },100 ) 

    }

 }

objFun.fun2(); // undefined,setTimeout指向全局(window),全局无fun2函数

1、箭头函数

箭头函数this指向函数定义时的this。箭头函数中没有this绑定,只能通过查找作用域,若箭头函数被非箭头函数包含,this执行的是最近一层的非箭头函数this。

fun2: function () {

    setTimeout(() => { this.fun1() },100)

}

objFun.fun2(); // local_a

2、中间变量 _this = this

fun2: function () { 

    var _this = this;

    setTimeout(() => { _this.fun1()  },100 )

}

objFun.fun2(); // local_a

3、apply、call、bind

三者都是改变this指向功能。

.apply(thisArg, [argsArrays])

.call(thisArg, arg1, arg2)

.bind(thisArg, arg1, arg2)()  // 创建一个新函数

fun2: function () { 

   setTimeout(() => {

         this.fun1()   

    }.apply(objFun),100);

}

objFun.fun2(); // local_a

4、new实例化

function Person(arg1, arg2) {

    this.first = arg1;

    this.last = arg2;

}

var person = new Person('name1','name2');

person.last; // arg2

5、闭包

var a = ‘window_a’;

function fn() {

    var a = ‘local_a’;

    return function fn1() { return "hello," + this.a }

}

fn();  // hello,local_a

相关文章

网友评论

      本文标题:this apply call bind

      本文链接:https://www.haomeiwen.com/subject/owzhsftx.html