new call apply bind 实现

JavaScript源码实现

1.new 实现

首先讲讲原型链
// 第一种方式:字面量
var o1 = {name: 'o1'}
var o2 = new Object({name: 'o2'})
// 第二种方式:构造函数
var M = function (name) { this.name = name; }
var o3 = new M('o3')
// 第三种方式:Object.create
var p = {name: 'p'}
var o4 = Object.create(p)

使用Object.create()是将对象继承到proto属性上
hasOwnProperty 不用遍历判断其属性

function myNew (){
    let Constructor = Array.prototype.shift.call(arguments);
    let obj  =  {};
    obj.__proto__ = Constructor.prototype;
    let result = Constructor.apply(obj,arguments);
    return typeof result === 'object' ? result : obj
}

2.call 接受多个参数 第一个为函数上下文也就是this,后面的参数为函数本身参数

Function.prototype.myCall = 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
}

3.apply()调用一个指定this值的函数, 接收作为一个数组或者类数组对象提供的参数

Function.prototype.myApply = function(context) {
    context = context ? Object(context) : window
    context.fn = this
    let args = [...arguments][1]
    if (!args) {
        return context.fn()
    }
    let r = context.fn(args)
    delete context.fn;
    return r
 }

4.bind可以绑定this执行为传入的对象
bind方法返回一个函数(高阶函数) 实现一个简易的bind方法

Function.prototype.my_bind = function() {
  let self = this, // 保存原函数
  context = Array.prototype.shift.call(arguments), // 保存需要绑定的this上下文
  args = Array.prototype.slice.call(arguments); // 剩余的参数转为数组
  return function() { // 返回一个新函数
      self.apply(context, Array.prototype.concat.call(args, Array.prototype.slice.call(arguments)));
  }
}

你可能感兴趣的:(new call apply bind 实现)