Why the property “prototype” is absent in definition methods of ES6 classes

*爱你&永不变心* 提交于 2019-12-06 11:35:01

问题


Es6, Classes there. We have the method (go) like this :

the example in ES6

class X{
   go(){}
}

var y = new X();
var z = new y.go();
console.log(z)

Example of the Error Screen Shot:

We don't have property prototype of this method (go), so we can't create new Object from this method. This is the fact. But I can't understand WHY? Why the developers of javascript in ES6 don't let me use this functionality.

Vice versa in ES5 we can create new instance from Object's methods. Of course, it works from prototype's methods too

the example in Es5

function X (){}
X.prototype.go = function(){}

var y = new X();
var z = new y.go();
console.log(z)

回答1:


But I can't understand WHY?

ES2015 distinguishes between two types of functions:

  • callable functions: functions that can be called without new, i.e. foo().
  • constructable functions: functions that can be called with new.

Whether a function is callable or constructable or both depends on how it is defined. The specification simply dictates that functions declared via the method syntax are not constructable.

Now, that doesn't explain the reasons behind this decision. I can't speak for the TC39 committee, but a clear effort with ES2015 was to reduce some of the surprising behaviors around functions. As such it was enforced how certain types of functions can be used. A method is conceptually not a constructor and thus you cannot call it as such.


Constructable functions:

  • Classes

Callable functions:

  • Arrow functions
  • Object/class methods (via method syntax)
  • Generator functions
  • Async functions

Both:

  • Function declarations/expressions


来源:https://stackoverflow.com/questions/53646225/why-the-property-prototype-is-absent-in-definition-methods-of-es6-classes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!