简体   繁体   中英

Functions vs. Objects in JavaScript and the instantiation without function

I know, that a function in JavaScript is nothing else than an object that has a prototype property with a constructor what can be used to instantiate new objects.

However, it is not possible to do the following:

 let Pear = {
    prototype : Object.prototype
 };
 let p = new Pear();  //Throws "caught TypeError: Pear is not a constructor"

In my opinion, this should be exactly the same like:

 function Pear() {

 }
 let p = new Pear();

what works. I am just wondering where the difference is. Is there a fix for my first way? Or are "functions" no "real" objects and get treated differently? It's really just a curiosity thing. Nothing important actually...

The object that new operates on must implement the [[Construct]] internal method, otherwise it will throw a TypeError exception (what you observed).

Knowing that, I don't believe you could use new in conjunction with an object produced with the object literal syntax.

However, if you're defining things like that, you probably don't want to. You could create a new Object including the properties of a former with Object.assign() .

let p = Object.assign({}, Pear);

Alternatively, you could use another way to change the prototype of the object to something else.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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