call, apply,bind的实现和使用方式

 Call函数 

为指定的this对象调用指定的函数,可以用它来实现方法的继承 和 函数bind等

语法:

fun.call(thisArg, arg1, arg2, ...)

参数:

thisArg: 一般情况下,指的是该函数(fun)要执行的上下文。 在 non-strict mode模式下,设置为null或者underfined的时候,指代的是window对象,在strict mode下会报错。设置为原始值(数字,字符串,布尔值)的时候,指的是原始值的自动包装对象。

arg: 传递给fun的参数,以列表形式传递

举例:

var numbers = [5, 6, 2, 3, 7]; 
var max = Array.prototype.slice.call(numbers , 1);
console.log(max); // [6, 2, 3, 7]

实现方式:

Function.prototype.call2 = function (context) {
    var self = context;
    if (typeof context === 'underfined' || typeof context === null) {
        // 非严格模式下, context为空或者underfined的时候 上下文指代的是window对象
        self = window;
    };
    if (typeof context === 'number' || typeof context === 'string' || typeof context === 'boolean') {
        self = new Object();
        self.key = context;
    }
    var params = [];
    for (var  i = 1; i< arguments.length; i++) {
        params.push(arguments[i]);
    };
    self.newFn = this;
    var result = self.newFn(...params)
    delete self.newFn;
    return  result;
}
var obj = {name: 1};
console.log(greet.apply2(obj, [10, 20])) // 30
console.log(obj) // {name: 1}

 Apply函数 

语法:

fun.apply(thisArg, [arg1, arg2, ..])

参数:

thisArg: 

一般情况下,指的是该函数(fun)要执行的上下文。 在 non-strict mode模式下,设置为null或者underfined的时候,指代的是window对象,在strict mode下会报错。设置为原始值(数字,字符串,布尔值)的时候,指的是原始值的自动包装对象。

arg: 传递给fun的参数,以数组形式传递

举例:

var numbers = [5, 6, 2, 3, 7]; 
var max = Array.prototype.slice.apply(numbers , [1]);
console.log(max); // [6, 2, 3, 7]

实现方式:

Function.prototype.apply2 = function (context) {
    var self = Object(context) || window;
    var params = arguments[1];
    if (params instanceof Array) {
    self.newFn = this; // 这里将要执行的函数当作self的属性执行
    var result = self.newFn(...params)
    delete self.newFn;
    return  result;
    }
    return false;
}
function greet (a, b) {
    return a + b
}

var obj = {name: 1};
console.log(greet.apply2(obj, [10, 20])) // 30
console.log(obj) // {{name: 1}}

 Bind函数 

绑定函数

bind函数和apply,call方法相同的是都会改变函数执行的上下文, 不同的是,bind执行后会不会立即执行绑定的函数,而是返回一个新的绑定函数,绑定函数包装了原函数对象,调用绑定函数通常会导致执行包装函数

var foo = {
    value: 1
};

function bar(name, age) {
    this.habit = 'shopping';
    console.log(this.value);
    console.log(name);
    console.log(age);
}

bar.prototype.friend = 'kevin';

var bindFoo = bar.bind(foo, 'daisy'); 
bindFoo(); //这里bindFoo是返回的绑定函数, 调用这个bindFoo的时候,会执行bar.call(foo, args)方法

偏函数

通过bind创建的绑定函数,可以预设初始参数(初始参数在bind(this, args)中的args中设置)。当绑定函数被调用的时候,设置的初始参数 会 跟调用函数时候传递的参数合并,并且顺序靠前

function list() {
  return Array.prototype.slice.call(arguments);
}


var leadingThirtysevenList = list.bind(null, 37); // 37就是预设参数

var list = leadingThirtysevenList();  // [37]

var list2 = leadingThirtysevenList([4,5,6,7]) // [4,5,6,7]为后期传参,会和预设参数合并,并且预设参数保持在前面 [37,4,5,6,7]

setTimeout + bind

在默认情况下,使用 window.setTimeout() 时,this 关键字会指向 window (或global)对象。 当我们想要将this指向对应的实例的时候,就需要使用bind对象改变上下文。


function LateBloomer() {
  this.petalCount = Math.ceil(Math.random() * 12) + 1;
}

// 在 1 秒钟后声明 bloom
LateBloomer.prototype.bloom = function() {
  window.setTimeout(this.declare.bind(this), 1000); //这里1s后调用LateBloomer的declare方法
};


LateBloomer.prototype.declare = function() {
  console.log('I am a beautiful flower with ' +
    this.petalCount + ' petals!');
};

var flower = new LateBloomer();
flower.bloom();  // 一秒钟后, 调用'declare'方法

作为构造函数使用的绑定函数

就是在bind返回了绑定函数之后, 将该函数作为构造函数,new 实例出来,这个时候原来bind提供的上下文this就会失效,取而代之的就是这个实例对象。

设定的参数列表依旧有效

function bar (age) {
  this.name = "xiaoyu";
  console.log(this.name + " gender is " + this.gender + " and age is " + age);
}
var foo = {gender: 1};
var bindFun = bar.bind(foo, 18);
bindFun();  // xiaoyu gender is 1 and age is 18

// 作为构造函数使用绑定函数的时候
var newFun = new bindFun(); // xiaoyu gender is undefined and age is 18 可以看到bindFun执行的上下文不再是foo对象,所以this.gender没有获取到值结果是underfined. 但是她设置的参数age: 18是任然生效的

语法:

fn.bind(thisArg, params1, params2, ....)

使用方法:

var numbers = [5, 6, 2, 3, 7]; 
var max = Array.prototype.slice.apply(numbers , 1, 3);
max(); // [6, 2]

实现方法:(实现bind的构造函数效果那里不明白

if (!Function.prototype.bind) {
  Function.prototype.bind = function(context) {
    if (typeof this !== 'function') {
      // closest thing possible to the ECMAScript 5
      // internal IsCallable function
      throw new TypeError('Function.prototype.bind - what is trying to be bound is not callable');
    }

    var params = Array.prototype.slice.call(arguments, 1), //获取传递的参数
        newFun = this,
        fBound  = function() {
          // this instanceof fBound === true时,说明返回的fBound被当做new的构造函数调用
          return newFun.apply(this instanceof fBound
                 ? this
                 : context,
                 // 获取调用时(fBound)的传参.bind 返回的函数入参往往是这么传递的
                 params.concat(Array.prototype.slice.call(arguments)));
        };

    // 维护原型关系
    if (this.prototype) {
      // Function.prototype doesn't have a prototype property
      fBound.prototype = this.prototype; 
    }

    return fBound;
  };
}

更多查看下篇js中apply, call,bind的区别,以及this指向性问题

https://tylermcginnis.com/this-keyword-call-apply-bind-javascript/

转载于:https://my.oschina.net/u/4085373/blog/3024166

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值