new、call、apply、bind实现

剖析 new 的内部原理

function Animal(name){
  this.name = name;
}
Animal.color = 'black';
Animal.prototype.say = function(){
  console.log(`I 'm ${this.name}`);
}
var cat = new Animal('cat'); 

new Animal('cat') = {
  var obj = {};
  obj.__proto__ = Animal.prototype;Ï
  var result = Animal.call(obj, 'cat');
  return typeof result === 'object' ? result : obj; 
}

思路:
将上述流程分为4个步骤来理解:
1.创建一个空对象obj;
2.把obj的proto指向构造函数Animal的原型对象 prototype,
此时便建立了obj对象的原型链obj->Animal.prototype->Object.prototype->null
3.在obj对象的执行环境调用Animal函数并传递参数‘cat’。相当于var result = obj.Animal('cat');
当这句执行完之后,obj便产生了属性name并赋值为‘cat’。
4.考察第3步的返回值,如果无返回值或者返回一个非对象值,则将obj作为新对象返回;否则会将result作为新对象返回;
或者写为

var new1 = function(func){
  var newObj = Object.create(func.prototype);
  var resultObj = func.call(newObj);
  if(typeof resultObj === 'object'){
    return resultObj;
  }else{
    return newObj;
  }
}

剖析call的内部原理 call(thisArgs, [, args...])

思路:
thisArgs的取值有以下四种情况:
1.不传,或者传null,undefined,函数中的this指向window对象
2.传递另一个函数的函数名,函数中的this指向这个函数的引用。
3.传递字符串、数值或布尔类型等基础类型,函数中的this指向其对应的包装对象,如String, Number,Boolean
4.传递一个对象,函数中的this指向这个对象
核心功能:它允许在一个对象上调用该对象没有定义的方法,并且这个方法可以访问该对象中的属性
换句话而言:call() 方法在使用一个制定的this值和若干个指定的参数值的前提下调用某个函数或方法。

var a = {
  name: 'onepixel', // 定义a的属性
  say: function(){
    console.log('hi, I'm function a');
  }
}
function b(name){
  console.log('Post params: '+ name);
  console.log('I 'm ' +this.name);
  this.say();
}
b.call(a, 'test');
>>
Post params: test
I 'm onepixel
I 'm function a
var foo = {
  value: 1
}
function bar(){
  console.log(this.value);
}
bar.call(foo);
>>>
var foo = {
  value: 1,
  bar: function(){
    console.log(this.value)
  }
}
bar.call(foo);  >>>>>>>>> foo.bar(); // 1

实现call:

// 步骤分为:1.将函数设为对象的属性;2.执行该函数;3.删除该函数;
Function.prototype.call2 = function(context){
  var context = 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;
}

剖析apply的内部原理

apply和call的唯一区别是第二个参数的传递方式不同,apply的第二个参数必须是一个数组(或者类数组),而call允许传递一个参数列表。
详见上面call的剖析

Function.prototype.apply2 = function(context, arr){
  var 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;
}

剖析bind的内部原理

思路
弥补了call/apply的不足,由于call/apply会对目标函数自动执行,从而导致他无法在事件绑定函数中使用,因为事件绑定函数不需要我们手动执行,它是在事件被触发时由js内部自动执行的。而bind在实现改变函数this的同时又不会自动执行目标函数,因此可以完美的解决上述问题。
换一句话而言:bind()方法会创建一个新函数。当这个新函数被调用时,bind()的第一个参数将作为他运行时的this,之后的一序列参数将会在传递的实参前传入作为它的参数。
特点:1.返回一个函数; 2.可以传入参数
需要说明的是:
1.在bind的时候 ,还可以传参,在执行bind返回的函数时,再传另一个参数
2.一个绑定函数也能使用new操作符创建对象:这种行为就像把原函数当成构造器。提供的this值被忽略,同时调用时的参数被提供给模拟函数。
实现

Function.prototype.bind2 = function(context){
  if(typeof this !== 'function'){
    throw new Error('Funtion.prototype.bind - what is trying to be bound is not callable');
  }
  vat fToBind = this;
  var args = Array.prototype.slice.call(arguments, 1);
  var fNOP = function(){};
  var fBound = function(){
    fToBind.apply(this instanceof fNOP ? this : context, args.concat(Array.prototype.slice.call(arguments)));
  }

  fNOP.prototype = this.prototype;
  fBound.prototype = new fNOP();

  return fbound;
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
禁止转载,如需转载请通过简信或评论联系作者。

推荐阅读更多精彩内容