博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
js bind实现
阅读量:7076 次
发布时间:2019-06-28

本文共 971 字,大约阅读时间需要 3 分钟。

  hot3.png

Function.prototype.bind2 = function(context){  if (typeof this !== "function") {    throw new Error("Function.prototype.bind - the object to be bound is not callable");  }  var self = this  var args = Array.prototype.slice.call(arguments,1)  var fNOP = function () {};  var boundFN = function(){    var bindargs = Array.prototype.slice.call(arguments)    self.apply(this instanceof self ? this: context,args.concat(bindargs))  }  fNOP.prototype = this.prototype;  boundFN.prototype = new fNOP()  return boundFN}var foo = {name : 'xxx'}function bar (age,sex,tall){  this.tall = tall  console.log(this.name);  console.log(age);  console.log(sex);  console.log(this.tall);}var dd = bar.bind2(foo,12,'male')var cc = new dd('180cm')console.log(cc)

其中

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

arguments是具有length属性的对象,该操作可以将形似数据的对象转换成数据,并传入参数进行数组截取。另外,注意使用slice而不是splice,相同点:都会返回截取后的数组,不同点:splice会对原数组进行截取,slice不是对原数组有影响。

转载于:https://my.oschina.net/pandon/blog/1816659

你可能感兴趣的文章