Trying to understand the new keyword

非 Y 不嫁゛ 提交于 2019-12-06 05:35:42

I'm trying to understand exactly what the javascript new keyword means

a = new X() means something like:

  • create new object A
  • set its prototype to the object called X.prototype (all functions have a "prototype" property which is just an object and you can modify it to add behaviour to objects created using this function and new),
  • call X with this=a to initialize the object.

This is similar to:

a = Object.create(/* prototype */ X.prototype, {});
a.constructor = X; /* magic property which can be read after */
X.apply(/* this */ a, /* args */[]);

why it is necessary and when I should use it.

It isn't and you don't have to. Object.create works more naturally with JS prototype-based object model and lets you create arbitrary prototype chains.

When new is used, it's used like this:

function Class(constructor_args) {
   // init an object
   this.a = 10;
};
Class.prototype.method1 = function() {
   console.log(this.a);
}
var obj = new Class();

Then after you create an object using new Class(), its prototype refers to the object Class.prototype which contains its methods while the object itself contains the fields.

(Personal opinion: The keyword new was introduced to make it easier in Javascript to write code which resembles Java/C++ and classical non-prototypal object model.)

Plase read these excellent articles:

Classical inheritance in Javascript

Prototypal inheritance

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