为什么我不能设置使用“绑定"创建的函数的“原型"? [英] Why can't I set the 'prototype' of a function created using 'bind'?
问题描述
考虑这个代码:
function foo(something) {
this.a = something;
}
var obj1 = {};
var bar = foo.bind(obj1);
现在不执行以下语句:
bar.prototype.newprop = "new"; // Cannot execute this
据我所知,每个函数都有一个原型对象.那为什么不能执行上面的语句呢?
As I understood, every function has a prototype object. Then why can't we execute the above statement?
bar 确实是一个我们可以称之为函数的函数:
And bar is indeed a function as we can call it:
bar(2);
console.log(obj1.a); // 2
推荐答案
据我所知,每个函数都有一个原型对象.
As I understood, every function has a prototype object.
嗯,每个规则都有例外:-) 你发现了一个:绑定函数没有 .prototype
属性,因为它们不需要它.当您使用 new
调用绑定函数时,它会调用原始函数作为构造函数,使用原始的 .prototype
对象作为新实例的原型.
Well, there are exceptions to every rule :-) You found one: bound functions don't have a .prototype
property because they don't need it. When you call a bound function with new
, it calls the original function as a constructor, using the original's .prototype
object as the prototype of the new instance.
事实上,由于 ECMAScript 6 很多函数没有带有对象的 .prototype
属性,因为它们不是构造函数 - 它们不能用 new
调用所以他们不需要它.其中有
In fact, since ECMAScript 6 many functions don't have a .prototype
property with an object, because they are not constructors - they cannot be called with new
so they don't need it. Among those are
- 箭头函数 (
() => {…}
) - 方法(
method() { ... }
在对象字面量和类中) - 内置非构造函数(如
Math.sin
)
- arrow functions (
() => {…}
) - methods (
method() { … }
in object literals and classes) - builtin non-constructor functions (like
Math.sin
)
这篇关于为什么我不能设置使用“绑定"创建的函数的“原型"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!