简体   繁体   English

为什么我们不能使用ES6箭头函数创建原型?

[英]Why can't we create prototypes using ES6 Arrow Functions?

First, I create a ES5 Function and then create it's prototype: 首先,我创建一个ES5函数,然后创建它的原型:

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

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 : 但是,当我使用ES6粗箭头功能创建相同的对象时,出现Cannot set property 'city' of undefined

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

Why is this? 为什么是这样?

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. 它们被设计为轻巧的,没有老式功能所带来的负担。

Another likely reason for this is that arrow functions capture the surrounding this rather than having it determined dynamically. 此另一个可能的原因是箭头功能捕获周围this ,而不是它动态地确定。 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. 因此,他们会表现不佳成为构造函数,因为this范围内他们将参照this从周围的范围,而不是对象被创建。 (In fact, you can't even use them as constructor functions. JavaScript will throw an error if you try to.) (实际上,您甚至不能将它们用作构造函数。如果您尝试这样做,JavaScript将会引发错误。)

From MDN : MDN

Use of prototype property 使用原型属性

Arrow functions do not have a prototype property. 箭头函数没有原型属性。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM