js中对一个bind返回的函数执行new时会怎样

function A(a,b){
    this.a=a;
    this.b=b
}
var a = A.bind({x:1},1)
var b = new a(2) // {a: 1, b: 2}

加上上一篇文章中说的情况,我们可以总结到,当我们对一个bind返回的函数进行操作时,实际上这种操作是对目标函数的操作,也就是调用bind的函数。下面我们看一下es5文档的说明。

When the [[Construct]] internal method of a function object, F that was created using the bind function is called with a list of arguments ExtraArgs, the following steps are taken:

Let target be the value of F’s [[TargetFunction]] internal property.
If target has no [[Construct]] internal method, a TypeError exception is thrown.
Let boundArgs be the value of F’s [[BoundArgs]] internal property.
Let args be a new list containing the same values as the list boundArgs in the same order followed by the same values as the list ExtraArgs in the same order.
Return the result of calling the [[Construct]] internal method of target providing args as the arguments.

文档里说到,执行new的时候,实际上是会执行目标函数,并且把所有的参数列表传进去,也就是bind的时候传进去的加上new时传进去的参数。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,我可以为您介绍JSbind函数的实现方法。 在JSbind函数是用来改变函数内部this的指向的,它会返回一个新的函数,这个新函数的this指向是我们指定的对象。 以下是一个简单的bind函数的实现示例: ```javascript Function.prototype.myBind = function(context) { if (typeof this !== 'function') { throw new TypeError('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; }; ``` 在这个函数,我们首先判断this是否为函数类型,如果不是,就抛出一个 TypeError,确保我们绑定的是一个函数。然后,我们保存this的引用,将传入的参数保存在args变量,创建一个fNOP函数,最后返回一个函数fBound。 在fBound函数内部,我们使用apply方法来调用原函数,并且将指定的this和参数传递给它。这里需要注意的是,如果我们使用new关键字来创建fBound函数的实例,那么this指向的就是这个实例对象,否则this指向的就是我们指定的context对象。 最后,我们使用原型链来继承原函数,并将fBound函数的原型指向fNOP的实例,这样我们就可以在fBound函数访问原函数的prototype属性了。 希望这个简单的bind函数实现可以帮助到您。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值