JavaScript/new.target:修订间差异
来自康健生活
| 第222行: | 第222行: | ||
可以看到 bar 和 User 的本质区别一个是函数一个是函数对象。所以不能说 new 出来的构造函数不能使用 bind,而是生成的构造函数的 object 类型不能使用 bind。 | 可以看到 bar 和 User 的本质区别一个是函数一个是函数对象。所以不能说 new 出来的构造函数不能使用 bind,而是生成的构造函数的 object 类型不能使用 bind。 | ||
=== 模拟实现 === | === 模拟实现 === | ||
<syntaxhighlight lang="javascript"> | |||
Function.prototype.bind = function(context){ | |||
if (typeof this !== "function") { | |||
throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable"); | |||
}; | |||
var args = Array.prototype.slice.call(arguments, 1), | |||
F = function(){}, | |||
self = this, | |||
bound = function(){ | |||
var innerArgs = Array.prototype.slice.call(arguments); | |||
var finalArgs = args.concat(innerArgs); | |||
return self.apply((this instanceof F ? this : context), finalArgs); | |||
}; | |||
F.prototype = self.prototype; | |||
bound.prototype = new F(); | |||
return bound; | |||
};</syntaxhighlight> | |||
{{unknown}} | |||
这个示例不适用与构造函数对象,所以进行更改。 | |||