最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Why can't we create prototypes using ES6 Arrow Functions? - Stack Overflow

programmeradmin0浏览0评论

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

var Person = function() {};

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

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

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:

let Person = () => {};

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

Why is this?

Share Improve this question asked Jul 19, 2018 at 7:12 AxelAxel 5,12118 gold badges75 silver badges146 bronze badges 5
  • "Arrow functions do not have a prototype property" --> developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… – Mark Commented Jul 19, 2018 at 7:14
  • Possible duplicate of Why cannot use lambda to define prototype function – Mark Commented Jul 19, 2018 at 7:16
  • Even you could do this, arrow functions are not constructable, i.e. they cannot be called with new. – Felix Kling Commented Jul 19, 2018 at 12:13
  • 1 Possible duplicate of Arrow function vs function declaration / expressions: Are they equivalent / exchangeable? – Felix Kling Commented Jul 19, 2018 at 12:14
  • @MarkMeyer No, this is not a duplicate of that question. This one is about attempting to use a prototype on an arrow function and the other is about assigning an arrow function to another function's prototype. – JLRishe Commented Aug 9, 2019 at 18:46
Add a comment  | 

1 Answer 1

Reset to default 21

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. 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.)

From MDN:

Use of prototype property

Arrow functions do not have a prototype property.

var Foo = () => {};
console.log(Foo.prototype); // undefined
发布评论

评论列表(0)

  1. 暂无评论