From the new
MDN docs it says:
The new keyword does the following things:
- Creates a blank, plain JavaScript object.
- Adds a property to the new object (
__proto__
) that links to the constructor function’s prototype object
How exactly is the prototype defined then? My thought was it would be:
- If it’s in a function (not using the
class
keyword), it would lookup to find if there is a[Constructor].prototype
declared somewhere and use that, and if not it would fallback to…(not sure?). As an example if the constructor is namedRange
it would lookup to see ifRange.prototype
is defined and use that as the prototype. - If it’s in a
class
then it would use every method or property to build the prototype up.
Is that more-or-less a correct understanding, or what might I be missing?
Advertisement
Answer
No matter whether the constructor is declared with class syntax or as a function
, the <constructor.prototype> object will always exist, even if never explicitly referred to. Example:
function FooFn() {} class FooClass{} console.log(FooFn.prototype); console.log(FooClass.prototype);
These .prototype
objects are plain objects which become the internal prototype of instances created with new
. They also have a .constructor
property pointing to the constructor (the function / class used to create an instance).
So it’s not exactly that
it would lookup to find if there is a [Constructor].prototype declared somewhere and use that
but rather that such a property always exists on functions and classes, and when an instance is created with new
, the object inside the .prototype
property becomes the internal prototype of the instance.
If it’s in a class then it would use every method or property to build the prototype up.
Not exactly – a class is mostly just syntactic sugar for a function. What this does:
class Foo { method() { console.log(); } }
is almost exactly (but not entirely) the same as
function Foo() {} Foo.prototype = function method() { console.log(); }
The methods are assigned to the class’s .prototype
object when the class declaration happens, not when an instance is created.
class X { xMethod() { } } console.log(X.prototype); console.log(X.prototype.hasOwnProperty('xMethod')); console.log(X.prototype === (new X).__proto__);