Javascript的New、Apply、Bind、Call知多少

开发 前端
Javascript中的apply、call、bind方法是前端代码开发中相当重要的概念,并且与this的指向密切相关。本篇文章我们将深入探讨这个关键词的作用,并尝试进行手动编写复现。

[[438565]]

1 写在前面

Javascript中的apply、call、bind方法是前端代码开发中相当重要的概念,并且与this的指向密切相关。本篇文章我们将深入探讨这个关键词的作用,并尝试进行手动编写复现。

阅读文章前,我们带着几个问题进行研究:

  • 用什么样的思路可以new关键字?
  • apply、bind、call这三个方法有什么区别?
  • 怎样手动实现一个apply、bind和call?

2 new关键词

new关键词的作用是执行一个构造函数,返回一个实例对象,根据构造函数的情况来确定是否可以接受参数的传递。

2.1 new的原理

使用new进行实例化对象,其步骤是:

  1. 创建一个新的空对象,即{}
  2. 将该对象构造函数的作用域赋给新对象,this指向新对象(即将新对象作为this的上下文)
  3. 执行构造函数中的代码,为这个新对象添加属性
  4. 如果该对象构造函数没有返回对象,则返回this
  1. function Person(){ 
  2.  this.name = "yichuan" 
  3.  
  4. const p = new Person(); 
  5. console.log(p.name);//"yichuan" 

我们可以看到当使用new进行实例化时,可以将构造函数的this指向新对象p。当不使用new时,此时构造函数的this指向window。

  1. function Person(){ 
  2.  this.name = "yichuan" 
  3.  
  4. const p = Person(); 
  5. console.log(p);//undefined 
  6. console.log(name);//"yichuan"   window.name 
  7. console.log(p.name);//"yichuan" is undefined 

当我们在构造函数中直接返回一个和this无关的对象时,使用new关键字进行实例化对象,新生成的对象就是构造函数返回的对象,而非构造函数的this的对象。

  1. function Person(){ 
  2.  this.name = "yichuan"
  3.   return {age:18}; 
  4.  
  5. const p = new Person(); 
  6. console.log(p);//{age:18} 
  7. console.log(p.name);//"undefined" 
  8. console.log(p.age);/18 

此外,当构造函数返回的不是一个对象,而是基础数据类型的值时,使用new创建新对象,会将构造函数返回的值以对象形式给新对象。

  1. function Person(){ 
  2.  this.name = "yichuan"
  3.   return "onechuan"
  4.  
  5. const p = new Person(); 
  6. console.log(p);//{name:"yichuan"
  7. console.log(p.name);//"yichuan" 

new关键词执行之后总是会返回一个对象,要么是实例,要么是return语句指定的对象。

2.2 手写new的实现

new被调用后大致做了哪些事情?

  1. 让实例可以访问私有属性
  2. 让实例可以访问构造函数原型(constructor.prototype)所在原型链上的属性
  3. 构造函数返回的最后结果是引用数据类型
  1. function new_object(ctor,...args){ 
  2.  //先要判断ctor是否为一个函数 
  3.   if(typeof ctor !== "function"){ 
  4.    throw "ctor must be a function"
  5.   } 
  6.   //创建一个空对象 
  7.   const obj = new Object(); 
  8.   //将实例obj可以访问到ctor原型所在原型链的属性 
  9.   obj.__proto__ = Object.create(ctor.prototype); 
  10.   //将构造函数的this指向实例对象obj 
  11.   const res = ctor.apply(obj,...args); 
  12.   //确保最后new返回的是一个对象 
  13.   const isObject = typeof res === "object" && typeof res!== null
  14.   const isFunction = typeof res === "function"
  15.   return isObject || isFunction ? res : obj; 

当然,我们还可以进行优化以下:

  1. function new_object() { 
  2.   // 1、获得构造函数,同时删除 arguments 中第一个参数 
  3.   const ctor = [].shift.call(arguments);//其实这里是借用了数组的shift方法 
  4.   // 2、创建一个空的对象并链接到原型,obj 可以访问构造函数原型中的属性 
  5.   const obj = Object.create(ctor.prototype); 
  6.   // 3、绑定 this 实现继承,obj 可以访问到构造函数中的属性 
  7.   const ret =ctor.apply(obj, arguments); 
  8.   // 4、优先返回构造函数返回的对象 
  9.   return ret instanceof Object ? ret : obj; 
  10. }; 

3 apply、bind以及call

apply、bind和call是挂载Function对象上的三个方法,调用这三个方法的必须是一个函数。

3.1 apply

apply() 方法调用一个具有给定 this 值的函数,以及作为一个数组(或类似数组对象)提供的参数。apply()方法可以改变函数this的指向,且立即执行函数。

注意:Chrome 14 以及 Internet Explorer 9 仍然不接受类数组对象。如果传入类数组对象,它们会抛出异常。

  1. func.apply(thisArg, [param1,param2,...]); 

在使用apply时,会将func的this指向改变为指向thisArg,然后以[param1,param2,...]参数数组作为参数输入。

  1. func(["red","green","blue"]); 
  2. func.apply(newFun, ["red","green","blue"]); 

我们可以看到都执行func时,第一个func函数的this指向的是window全局对象,而第二个func函数的this指向的是newFun。

  1. Function.prototype.apply = function (context, arr) { 
  2.     context = context ? Object(context) : window;  
  3.     context.fn = this; 
  4.    
  5.     let result; 
  6.    //判断有没有参数数组输入 
  7.     if (!arr) { 
  8.         result = context.fn(); 
  9.     } else { 
  10.         result = context.fn(...arr); 
  11.     } 
  12.    //此处也可以使用eval进行处理 
  13.    // const result = eval("context.fn(...arr)"); 
  14.        
  15.     delete context.fn 
  16.     return result; 

3.2 bind

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

  1. bind(thisArg,param1,param2,...); 

其实,bind的实现思路基本和apply一致,但是在最后实现返回结果时,bind不需要直接执行,而是以返回函数的形式返回结果,之后再通过执行这个结果即可。

先分析下bind的特性:首先是指定新对象this指向,再传入参数返回一个定义的函数,最后使用柯里化进行调用。同样的,我们也可以根据这些特性进行手动封装一个bind函数:

  1. Function.prototype.bind = function(context){ 
  2.  //先要判断调用bind函数的是不是函数,需要抛出异常 
  3.   if(typeof this !== "function"){ 
  4.    throw new Error("this bind function must be userd to function"); 
  5.   } 
  6.   //存储this的指向 
  7.   const self = this; 
  8.   //context是新对象this指向的目标对象,而参数就是在第一个参数之后的参数 
  9.   const args = Array.prototype.slice.call(arguments,1); 
  10.    
  11.   //创建一个空对象 
  12.   const fun = function(){} 
  13.    
  14.   //返回一个函数 
  15.   const funBind = function(){ 
  16.    //返回所有的参数给bind函数 
  17.     const bindArg = Array.prototype.slice.call(arguments); 
  18.     //将传入的参数合并成一个新的参数数组,作为self.apply()的第二个参数 
  19.     return self.apply(this instanceof fun ? this : context,  args.concat(bindArgs)); 
  20.     /**********************说明************************************/ 
  21.   } 
  22.    
  23.   //空对象的原型指向绑定函数的原型 
  24.   fun.prototype = this.prototype; 
  25.   //空对象的实例赋值给 funBind.prototype 
  26.   funBind.prototype = new fun(); 
  27.   return funBinf; 

补充说明:

  • this instanceof fun返回为true时,表示的是fun是一个构造函数,其this指向实例,直接将context作为参数输入
  • this instanceof fun返回为false时,表示的是fun是一个普通函数,其this指向顶级对象window,将绑定函数的this指向context对象

当然,我们也可以写成这种形式:

  1. Function.prototype.bind = function(context,...args){ 
  2.  //先要判断调用bind函数的是不是函数,需要抛出异常 
  3.   if(typeof this !== "function"){ 
  4.    throw new Error("this bind function must be userd to function"); 
  5.   } 
  6.   //存储this的指向 
  7.   const self = this; 
  8.    
  9.   const fBind = function(){ 
  10.    self.apply(this instanceof self ? this: context, args.concat(Array.prototype.slice.call(arguments)));  
  11.   } 
  12.   if(this.prototype){ 
  13.    fBind.prototype = Object.create(this.prototype); 
  14.   } 
  15.   return fBind; 

注意:Object.create()是es2015语法引入的新特性,因此在IE<9的浏览器是不支持的。

3.3 call

call() 方法使用一个指定的 this 值和单独给出的一个或多个参数来调用一个函数。使用调用者提供的 this 值和参数调用该函数的返回值。若该方法没有返回值,则返回 undefined。

  1. function.call(thisArg, param1, param2, ...) 

注意:该方法的语法和作用与 apply() 方法类似,只有一个区别,就是 call() 方法接受的是一个参数列表,而 apply() 方法接受的是一个包含多个参数的数组。

call函数的实现:

  1. Function.prototype.call = function(context,...args){ 
  2.   //将函数设置为对象的属性 
  3.  context = context || window; 
  4.   context.fn = this; 
  5.    
  6.   //执行函数 
  7.   const result = eval("context.fn(...args)"); 
  8.   //删除对象的这个属性 
  9.   delete context.fn; 
  10.   return result; 

4 参考文章

  • 《解析 bind 原理,并手写 bind 实现》
  • 《解析 call/apply 原理,并手写 call/apply 实现》
  • 《Javascript核心原理精讲》

5 写在最后

在这篇文章中,我们知道apply、bind、call的区别在于:

  • apply、call改变了this指向后,会立即进行调用函数,返回的是执行结果
  • bind在改变this指向后,返回的是一个函数,需要另外再进行调用一次
  • bind、call传递的第一个参数都是this将要指向的对象,后面都是一个一个参数的形式输入
  • apply传递的第一个参数也是this将要指向的对象,后面传递的第二个参数是一个参数数组

 

责任编辑:姜华 来源: 前端万有引力
相关推荐

2021-06-18 07:16:17

JavaScript apply()方法call()方法

2024-03-15 08:21:17

bindJavaScrip函数

2017-10-10 14:36:07

前端Javascriptapply、call、

2015-03-02 09:22:09

Javascript函数用法apply

2021-12-04 11:17:32

Javascript继承编程

2011-03-22 09:49:15

JavaScript

2021-06-09 07:01:30

前端CallApply

2021-12-10 07:47:30

Javascript异步编程

2021-11-30 06:56:58

CallApply函数

2021-12-03 15:24:45

Javascript数据类型

2021-12-11 18:59:35

JavascriptJSON应用

2021-12-07 08:01:33

Javascript 垃圾回收机制前端

2021-12-06 07:15:48

Javascript作用域闭包

2012-02-13 22:50:59

集群高可用

2022-05-08 18:02:11

tunnel隧道云原生

2022-07-13 09:00:06

BindNew 操作

2010-08-16 09:15:57

2013-12-23 14:00:31

Windows 8.2Windows 8.1

2017-07-14 10:51:37

性能优化SQL性能分析

2018-08-31 10:53:25

MySQL存储引擎
点赞
收藏

51CTO技术栈公众号