美文网首页
Function扩展

Function扩展

作者: 牛耀 | 来源:发表于2018-09-25 22:49 被阅读0次
  1. Function.prototype.bind(obj) :
  • 作用: 将函数内的this绑定为obj, 并将函数返回
  1. 面试题: 区别bind()与call()和apply()?
  • 都能指定函数中的this
  • call()/apply()是立即调用函数
  • bind()是将函数返回
var obj = {username: 'kobe'};
    /*function foo(){
        console.log(this);
    }*/
    function foo(data){
        console.log(this, data);
    }
    // foo();
    // foo.call(obj);
    // foo.apply(obj);
    //传入参数的形式
    // foo.call(obj, 33);//直接从第二个参数开始,依次传入
    // foo.apply(obj, [33]);//第二参数必须是数组,传入的参数放在数组里
    //bind的特点:绑定完this不会立即调用当前的函数,而是将函数返回
    /*var bar = foo.bind(obj);
    console.log(bar);
    bar();*/
    //bind传参的方式同call一样
    foo.bind(obj, 33)();
    setTimeout(function(){
        console.log(this);
    }.bind(obj), 1000);

相关文章

网友评论

      本文标题:Function扩展

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