JavaScript中的call(),apply(),bind()的用法

1.call()  apply(). bind()都是用来重定义this这个对象的!

如:

 

obj.myFun.call(db);    // 德玛年龄 99
obj.myFun.apply(db);    // 德玛年龄 99
obj.myFun.bind(db)();   // 德玛年龄 99

bind返回的是一个新的函数,你必须调用它才会被执行

2,对比call,bind,apply 传参情况


obj.myFun.call(db,'成都','上海');     // 德玛 年龄 99  来自 成都去往上海
obj.myFun.apply(db,['成都','上海']);      // 德玛 年龄 99  来自 成都去往上海  
obj.myFun.bind(db,'成都','上海')();       // 德玛 年龄 99  来自 成都去往上海
obj.myFun.bind(db,['成都','上海'])();   // 德玛 年龄 99  来自 成都, 上海去往 undefined

 


在JavaScript中,存在几种方法能够修改函数的 this 上下文:


  1. call()call() 方法接收一个参数列表,其中首个参数是函数运行时使用的 this 值,接下来的参数则是传递给函数的参数。例如:

    function myFunction(arg1, arg2) {
      console.log(this, arg1, arg2);
    }
    
    var obj = {name: 'obj'};
    myFunction.call(obj, 'arg1', 'arg2');
    

    运行上述代码,myFunction的 this 将指向 obj 对象,并打印出 {name: 'obj'}, 'arg1', 'arg2'

  2. apply()apply() 方法的工作方式与 call() 相似,区别仅在于 apply() 接收两个参数,此中第一个是函数执行时的 this 值,而第二个是一个数组(或类数组对象),其元素将作为参数传递给函数。

    function myFunction(arg1, arg2) {
      console.log(this, arg1, arg2);
    }
    
    var obj = {name: 'obj'};
    myFunction.apply(obj, ['arg1', 'arg2']);
    

    在这个例子中,myFunction 中的 this 将再次指向 obj,并打印出 {name: 'obj'}, 'arg1', 'arg2'

  3. bind()bind() 方法创建一个新的函数,在 bind() 被调用时,这个新函数的 this 被指定为 bind() 的第一个参数,而其余参数将作为新函数的参数供调用时使用。

    function myFunction(arg1, arg2) {
      console.log(this, arg1, arg2);
    }
    
    var obj = {name: 'obj'};
    var boundFunction = myFunction.bind(obj, 'arg1', 'arg2');
    boundFunction();
    

    在这个示例中,当调用 boundFunction() 时,myFunction() 中的 this 指向 obj 并打印出 {name: 'obj'}, 'arg1', 'arg2'


请注意,这些方法不能修改箭头函数的 this 值,因为箭头函数会捕获它们创建时的 this 值。







































posted @ 2022-03-15 16:15  踏浪小鲨鱼  阅读(40)  评论(0)    收藏  举报