call,apply,bind,new实现代码

call

ES3实现方式javascript

Function.prototype.call = function (context) {
    context = context ? Object(context) : window; 
    context.fn = this;

    var args = [];
    for(var i = 1, len = arguments.length; i < len; i++) {
        args.push('arguments[' + i + ']');
    }
    var result = eval('context.fn(' + args +')');

    delete context.fn
    return result;
}
复制代码

ES6实现方式java

Function.prototype.call = function (context) {
  context = context ? Object(context) : window; 
  context.fn = this;

  let args = [...arguments].slice(1);
  let result = context.fn(...args);

  delete context.fn
  return result;
}
复制代码

apply

ES3实现方式app

Function.prototype.apply = function (context, arr) {
    context = context ? Object(context) : window; 
    context.fn = this;

    var result;
    // 判断是否存在第二个参数
    if (!arr) {
        result = context.fn();
    } else {
        var args = [];
        for (var i = 0, len = arr.length; i < len; i++) {
            args.push('arr[' + i + ']');
        }
        result = eval('context.fn(' + args + ')');
    }

    delete context.fn
    return result;
}
复制代码

ES6实现方式函数

Function.prototype.apply = function (context, arr) {
    context = context ? Object(context) : window; 
    context.fn = this;
  
    let result;
    if (!arr) {
        result = context.fn();
    } else {
        result = context.fn(...arr);
    }
      
    delete context.fn
    return result;
}
复制代码

bind

Function.prototype.bind2 = function (context) {

    if (typeof this !== "function") {
      throw new Error("Function.prototype.bind - what is trying to be bound is not callable");
    }

    var self = this;
    var args = Array.prototype.slice.call(arguments, 1);

    var fNOP = function () {};

    var fBound = function () {
        var bindArgs = Array.prototype.slice.call(arguments);
        return self.apply(this instanceof fNOP ? this : context, args.concat(bindArgs));
    }

    fNOP.prototype = this.prototype;
    fBound.prototype = new fNOP();
    return fBound;
}
复制代码

new

function create() {
	// 一、得到构造函数,同时删除 arguments 中第一个参数
    Con = [].shift.call(arguments);
	// 二、建立一个空的对象并连接到原型,obj 能够访问构造函数原型中的属性
    var obj = Object.create(Con.prototype);
	// 三、绑定 this 实现继承,obj 能够访问到构造函数中的属性
    var ret = Con.apply(obj, arguments);
	// 四、优先返回构造函数返回的对象
	// 这是为了应付构造函数有返回对象的状况,下面给出实例
	return ret instanceof Object ? ret : obj;
};
复制代码

new 第4点实例解释

1.构造函数返回一个对象ui

function Car(color, name) {
    this.color = color;
    return {
        name: name
    }
}

var car = new Car("black", "BMW");
car.color;
// undefined

car.name;
// "BMW"
复制代码

2.构造函数没有return,返回undifinethis

function Car(color, name) {
    this.color = color;
}

var car = new Car("black", "BMW");
car.color;
// black

car.name;
// undefined
复制代码

3.构造函数有返回值,可是返回的不是对象spa

function Car(color, name) {
    this.color = color;
    return "new car";
}

var car = new Car("black", "BMW");
car.color;
// black

car.name;
// undefined
复制代码
相关文章
相关标签/搜索