Why the property “prototype” is absent in definiti

2020-07-26 13:50发布

问题:

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