为什么我们不能使用ES6箭头函数创建原型? [英] Why can't we create prototypes using ES6 Arrow Functions?

查看:412
本文介绍了为什么我们不能使用ES6箭头函数创建原型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先,我创建一个ES5函数,然后创建它的原型:

First, I create a ES5 Function and then create it's prototype:

var Person = function() {};

Person.prototype.city = function() {return 'New York'}

我在这里没有任何错误.但是,当我使用ES6粗箭头功能创建相同内容时,会得到Cannot set property 'city' of undefined:

I get no error in here. But when I create the same with ES6 fat arrow function, I get Cannot set property 'city' of undefined:

let Person = () => {};

Person.prototype.city = () => {return 'New York'}

这是为什么?

推荐答案

由于定义,箭头函数没有原型.它们被设计为轻巧的,没有老式功能所带来的负担.

Because by definition, arrow functions don't have prototypes. They're designed to be lightweight, without some of the baggage that old-style functions have.

另一个可能的原因是箭头功能捕获了周围的this而不是动态确定它.因此它们不能很好地用作构造函数,因为其中的this将从周围的范围而不是要创建的对象中引用this. (实际上,您甚至不能将它们用作构造函数.如果您尝试这样做,JavaScript将会抛出错误.)

Another likely reason for this is that arrow functions capture the surrounding this rather than having it determined dynamically. So they would serve poorly as constructor functions because the this within them would be referring to the this from the surrounding scope instead of the object being created. (In fact, you can't even use them as constructor functions. JavaScript will throw an error if you try to.)

来自 MDN :

原型属性的使用

箭头功能没有原型属性.

Use of prototype property

Arrow functions do not have a prototype property.

var Foo = () => {};
console.log(Foo.prototype); // undefined

这篇关于为什么我们不能使用ES6箭头函数创建原型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆