1836

The new keyword in JavaScript can be quite confusing when it is first encountered, as people tend to think that JavaScript is not an object-oriented programming language.

  • What is it?
  • What problems does it solve?
  • When is it appropriate and when not?
Bergi
  • 513,640
  • 108
  • 821
  • 1,164
Alon Gubkin
  • 53,054
  • 52
  • 181
  • 282
  • 12
    Also, related thread - http://stackoverflow.com/questions/383402/is-javascript-s-new-keyword-considered-harmful – Chetan S Oct 29 '09 at 22:04
  • 1
    read these examples first folks, https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/new – Martian2049 Dec 30 '18 at 17:00

16 Answers16

2209

It does 5 things:

  1. It creates a new object. The type of this object is simply object.
  2. It sets this new object's internal, inaccessible, [[prototype]] (i.e. __proto__) property to be the constructor function's external, accessible, prototype object (every function object automatically has a prototype property).
  3. It makes the this variable point to the newly created object.
  4. It executes the constructor function, using the newly created object whenever this is mentioned.
  5. It returns the newly created object, unless the constructor function returns a non-null object reference. In this case, that object reference is returned instead.

Note: constructor function refers to the function after the new keyword, as in

new ConstructorFunction(arg1, arg2)

Once this is done, if an undefined property of the new object is requested, the script will check the object's [[prototype]] object for the property instead. This is how you can get something similar to traditional class inheritance in JavaScript.

The most difficult part about this is point number 2. Every object (including functions) has this internal property called [[prototype]]. It can only be set at object creation time, either with new, with Object.create, or based on the literal (functions default to Function.prototype, numbers to Number.prototype, etc.). It can only be read with Object.getPrototypeOf(someObject). There is no other way to set or read this value.

Functions, in addition to the hidden [[prototype]] property, also have a property called prototype, and it is this that you can access, and modify, to provide inherited properties and methods for the objects you make.


Here is an example:

ObjMaker = function() {this.a = 'first';};
// ObjMaker is just a function, there's nothing special about it that makes 
// it a constructor.

ObjMaker.prototype.b = 'second';
// like all functions, ObjMaker has an accessible prototype property that 
// we can alter. I just added a property called 'b' to it. Like 
// all objects, ObjMaker also has an inaccessible [[prototype]] property
// that we can't do anything with

obj1 = new ObjMaker();
// 3 things just happened.
// A new, empty object was created called obj1.  At first obj1 was the same
// as {}. The [[prototype]] property of obj1 was then set to the current
// object value of the ObjMaker.prototype (if ObjMaker.prototype is later
// assigned a new object value, obj1's [[prototype]] will not change, but you
// can alter the properties of ObjMaker.prototype to add to both the
// prototype and [[prototype]]). The ObjMaker function was executed, with
// obj1 in place of this... so obj1.a was set to 'first'.

obj1.a;
// returns 'first'
obj1.b;
// obj1 doesn't have a property called 'b', so JavaScript checks 
// its [[prototype]]. Its [[prototype]] is the same as ObjMaker.prototype
// ObjMaker.prototype has a property called 'b' with value 'second'
// returns 'second'

It's like class inheritance because now, any objects you make using new ObjMaker() will also appear to have inherited the 'b' property.

If you want something like a subclass, then you do this:

SubObjMaker = function () {};
SubObjMaker.prototype = new ObjMaker(); // note: this pattern is deprecated!
// Because we used 'new', the [[prototype]] property of SubObjMaker.prototype
// is now set to the object value of ObjMaker.prototype.
// The modern way to do this is with Object.create(), which was added in ECMAScript 5:
// SubObjMaker.prototype = Object.create(ObjMaker.prototype);

SubObjMaker.prototype.c = 'third';  
obj2 = new SubObjMaker();
// [[prototype]] property of obj2 is now set to SubObjMaker.prototype
// Remember that the [[prototype]] property of SubObjMaker.prototype
// is ObjMaker.prototype. So now obj2 has a prototype chain!
// obj2 ---> SubObjMaker.prototype ---> ObjMaker.prototype

obj2.c;
// returns 'third', from SubObjMaker.prototype

obj2.b;
// returns 'second', from ObjMaker.prototype

obj2.a;
// returns 'first', from SubObjMaker.prototype, because SubObjMaker.prototype 
// was created with the ObjMaker function, which assigned a for us

I read a ton of rubbish on this subject before finally finding this page, where this is explained very well with nice diagrams.

DaveFar
  • 6,260
  • 3
  • 39
  • 80
Daniel Howard
  • 7,576
  • 2
  • 13
  • 2
  • 1
    @daniel, +1 for goodness. How did you find out what new does? – hvgotcodes Jan 10 '11 at 20:56
  • 50
    Just wanted to add: There is in fact a way to access the internal [[prototype]], by \_\_proto\_\_. This is however non-standard, and only supported by relatively new browsers (and not all of them). There is a standardized way coming up, namely Object.getPrototypeOf(obj), but it is Ecmascript3.1, and is itself only supported on new browers - again. It is generally recommended to not use that property though, stuff gets complicated real fast inside there. – Blub Apr 14 '11 at 14:55
  • 2
    I think this is also explained in the classic [MDC docs](https://developer.mozilla.org/en/JavaScript/Guide/Details_of_the_Object_Model). – artur May 11 '11 at 00:39
  • 2
    You can actually access the internal prototype object of the object via __ proto __ or this.constructor.prototype. – Art Aug 31 '11 at 22:14
  • 10
    Question: what happens differently if `ObjMaker` is defined as a function that returns a value? – Jim Blackler Feb 27 '12 at 19:05
  • 3
    Note that `ObjMaker = function() {this.a = 'first';};` when you calling just ObjMaker(), you are assigning `first` to global object, usually window, but when you call new ObjMaker(), this is pointing current object so you can call `new ObjMaker().a` – Cemo May 22 '12 at 18:06
  • 2
    George Mauer is right, only I think it is better to think of 'creating a new object from a base object' and 'copying the base object's prototype to the new object', than of creating a 'new instance', which is a concept that really belongs to class-based inheritance, not prototype-based inheritance. I have hopefully edited the question to reflect this... – silasdavis May 29 '12 at 10:41
  • Perhaps that's not quite right.. An instance under prototype inheritance is exactly an object whose prototype contains the prototype of a base object; `a` might diverge from being an instance of `A` after being created `var a = new A()`, and `var b = {}` might converge into being an instance of `A` via `b.__proto__ = A.prototype`. In any case I don't think there is a chain of references maintained like in a class inheritance, it is all by virtue of the copying (and overwriting) of the prototype. – silasdavis May 29 '12 at 10:53
  • 4
    That's all good and interesting, but it doesn't answer an important part of the question. Especially, when the use of `new` is appropriate and when not. I can write a function that returns an object with functions, just like you can write a "class" definition. I can use methods of such an object when I use `var obj = new func()` as well as just `var obj = func()`, e.g. `obj.method()` works fine in both cases. It's the same to me right now. I don't use the `this` keyword though, I don't need it. Do I need `new`? – ygoe Sep 24 '12 at 21:09
  • Doesn't the new keyword also set the 'constructor' property of the instance to the constructor function – sanz Oct 14 '12 at 23:22
  • @LonelyPixel Maybe if you looked at JulianR's equally-excellent answer, below. – Engineer Oct 23 '12 at 17:14
  • @NickWiggill He uses `this`, I don't. – ygoe Oct 23 '12 at 21:25
  • 14
    @LonelyPixel `new` exists _so that you don't have to_ write factory methods to construct/copy functions/objects. It means, "Copy this, making it just like its parent 'class'; do so efficiently and correctly; and store inheritance info that is accessible only to me, JS, internally". To do so, it modifies the otherwise inaccessible internal `prototype` of the new object to opaquely encapsulate the inherited members, mimicking classical OO inheritance chains (which aren't runtime modifiable). You can simulate this without `new`, but inheritance will be runtime modifiable. Good? Bad? Up to you. – Engineer Oct 23 '12 at 22:36
  • 1
    @LonelyPixel ...And when using new, the meaning of this is modified to refer to the object just created via new -- exactly as when you create an object using brace-format (a la JSON) without new. So again, new can be completely circumvented. It has been stated elsewhere that new is actually a bit slower than creating an empty object. In any case, the future is Object.create(). I think it's fair to say that what you're already doing is probably similar to [Crockford's explicit Object.create()](http://javascript.crockford.com/prototypal.html) from before it was added to the ES5 standard. – Engineer Oct 23 '12 at 23:32
  • @hvgotcodes you can get complete js internals here. http://www.ecma-international.org/publications/standards/Ecma-262.htm – Kamal Reddy Apr 23 '13 at 14:28
  • 11
    a small point to add: a call to a constructor, when preceded by the new keyword, automatically returns the created object; there is no need to explicitly return it from within the constructor. – charlie roberts Jun 06 '13 at 02:04
  • 1
    I ran a little JSFiddle test to see how the this object works in relation to the new keyword if anybody is interested: http://jsfiddle.net/yux2a/1/ – Robert Massaioli Aug 04 '13 at 11:40
  • 7
    There is a note that says `Notice that this pattern is deprecated!`. What is the correct up-to-date pattern to set the prototype of a class? – Tom Pažourek Feb 17 '14 at 12:18
  • 6
    @tomp `SubObjMaker.prototype = Object.create(ObjMaker.prototype);` and you may need a [shim](https://github.com/es-shims/es5-shim) for `Object.create`. – wbyoung Mar 06 '14 at 18:48
  • @silasdavis is there an example that you can give that shows that _[[prototype]]_ is a copy of _Constructor.prototype_ at the time that `new` is used? Either I'm not understanding or something [different is happening](http://jsfiddle.net/we97N/2/) from what you're explaining. – wbyoung Mar 06 '14 at 19:17
  • I found the following information that explains how _[[prototype]]_ or *__proto__* work [here](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/proto) and updated the answer to reflect the fact that _[[prototype]]_ is not actually copied. @silasdavis I'd love for you to review these changes. – wbyoung Mar 06 '14 at 19:42
  • 1
    Here another detailed explanation about creating new objects. It helps me understanding very well differences about object creation, the constructor property, prototype chaining: http://davidwalsh.name/javascript-objects-deconstruction – yuri May 21 '14 at 10:11
  • 2
    @tomp I found a nice [blog](http://blog.brillskills.com/2013/09/javascript-subclassing-using-object-create/) explaining the problem a little bit more. – rene Jun 04 '14 at 09:41
  • Oh my. In all my years of using javascript, I never knew this. Also the 'so java checks its prototype' is a live check. For example, if Test2 is constructed from Test1 beforehand, and Test1 adds a new function afterwards, Test2 still has access to that function. Simply amazing. – Verron Knowles Jun 10 '14 at 07:01
  • 1
    @wbyoung You misunderstood. It is not a copy, it is a reference to the same object Constructor.prototype is referencing. An assignment `Constructor.prototype = {...}` can make the constructor reference a different prototype object later on, to be used in subsequent constructions, but the object [[prototype]] referenced by the already created objects stays the same. – masterxilo May 01 '16 at 01:42
  • @masterxilo yes, the [changes that I made on 3/6/14](http://stackoverflow.com/revisions/3658673/15) are in line with what you're saying. – wbyoung May 04 '16 at 23:52
  • Great explanation - missing only an example of what happens when returning a new object from the Construction function. – kernix May 09 '16 at 06:53
  • 1
    http://www.2ality.com/2014/01/new-operator.html - This Explains it - No Fuss , No Confusion – Karan Kaw Feb 24 '17 at 10:50
  • This answer, in conjunction with this other answer to [How does JavaScript .prototype work?](https://stackoverflow.com/a/4778408/2446144) really made it clear for me! – Jose V Jul 14 '19 at 11:29
  • This lacks an explanation of what calling a constructor function without new does... If you're wondering what the answer is see [below](https://stackoverflow.com/a/1646957). – Zac Taylor Dec 17 '19 at 21:28
421

Suppose you have this function:

var Foo = function(){
  this.A = 1;
  this.B = 2;
};

If you call this as a standalone function like so:

Foo();

Executing this function will add two properties to the window object (A and B). It adds it to the window because window is the object that called the function when you execute it like that, and this in a function is the object that called the function. In Javascript at least.

Now, call it like this with new:

var bar = new Foo();

What happens when you add new to a function call is that a new object is created (just var bar = new Object()) and that the this within the function points to the new Object you just created, instead of to the object that called the function. So bar is now an object with the properties A and B. Any function can be a constructor, it just doesn't always make sense.

apsillers
  • 101,930
  • 15
  • 206
  • 224
JulianR
  • 15,427
  • 3
  • 48
  • 84
  • 7
    Depends on execution context. In my case (Qt scripting) it's just a global object. – MaksymB Jan 21 '13 at 13:24
  • 2
    will this cause more memory usage? – Jürgen Paul Jul 24 '13 at 19:20
  • 2
    *because window is the object that called the function* - must be: because window is the object that **contains** the function. – Dávid Horváth Jul 23 '16 at 13:22
  • @DávidHorváth Then why is it that when we nest a function inside of another, and call it inside that parent function, `this` is still the `window`, even when the function was nested inside of another function and not `window`? – doubleOrt Sep 10 '17 at 15:50
  • 2
    @Taurus In a web browser a non-method function will be a method of `window` implicitly. Even in a closure, even if anonymus. However, in the example it is a simple method invocation on window: `Foo();` => `[default context].Foo();` => `window.Foo();`. In this expression `window` is the *context* (not only the *caller*, which does not matter). – Dávid Horváth Sep 11 '17 at 11:47
  • @DávidHorváth Good to know, Thanks! So no matter what, `this` always points to the context a method/function is declared at and not where it is called. Am i on the right track ? – doubleOrt Sep 11 '17 at 11:54
  • 1
    @Taurus Basicly yes. However in ECMA 6 and 7 things are more complex (see lambdas, classes, etc). – Dávid Horváth Sep 11 '17 at 12:00
  • @Taurus One more note to this. Context and "declaration place" are not the same. You can invoke a method with an other context with `.call()` and `.apply()` (or just assign with an other object's property). So there are three independent concept here: place of definition, context, and caller environment. – Dávid Horváth Sep 11 '17 at 14:44
  • @DávidHorváth Couldn't you just say that a (function/method)'s context is by default where it is contained at but we can change that default via `call` and `apply` instead of the 3 independent concepts ? What do you mean by "caller environment" ? – doubleOrt Sep 11 '17 at 16:46
171

In addition to Daniel Howard's answer, here is what new does (or at least seems to do):

function New(func) {
    var res = {};
    if (func.prototype !== null) {
        res.__proto__ = func.prototype;
    }
    var ret = func.apply(res, Array.prototype.slice.call(arguments, 1));
    if ((typeof ret === "object" || typeof ret === "function") && ret !== null) {
        return ret;
    }
    return res;
}

While

var obj = New(A, 1, 2);

is equivalent to

var obj = new A(1, 2);
basilikum
  • 9,714
  • 4
  • 38
  • 55
  • 76
    I found that javascript is easier to understand than english :v – damphat Oct 20 '13 at 10:11
  • 1
    Excellent answer. I have one tiny question: How can it be possible for `func.prototype` to be `null`? Could you please elaborate a bit on that? – Tom Pažourek Apr 02 '14 at 11:12
  • 6
    @tomp you could override the prototype property, by simply writing `A.prototype = null;` In that case `new A()` will result in on object, thats internal prototype points to the `Object` object: http://jsfiddle.net/Mk42Z/ – basilikum Apr 28 '14 at 18:19
  • 3
    The typeof check might be wrong because a host object could produce something different than "object" or "function". To test if something is an object, I prefer `Object(ret) === ret`. – Oriol Oct 08 '15 at 21:40
  • 3
    @Oriol thank you for the comment. It is true what you say and any actual test should be done in more robust way. However, I think for this conceptual answer, the `typeof` test just makes it easier to understand what is going on behind the scenes. – basilikum Oct 08 '15 at 21:53
122

For beginners to understand it better

try out the following code in the browser console.

function Foo() { 
    return this; 
}

var a = Foo();       //returns window object
var b = new Foo();   //returns empty object of foo

a instanceof Window;  // true
a instanceof Foo;     // false

b instanceof Window;  // false
b instanceof Foo;     // true

Now you can read the community wiki answer :)

Community
  • 1
  • 1
Anulal S
  • 5,824
  • 5
  • 21
  • 31
39

so it's probably not for creating instances of object

It's used exactly for that. You define a function constructor like so:

function Person(name) {
    this.name = name;
}

var john = new Person('John');

However the extra benefit that ECMAScript has is you can extend with the .prototype property, so we can do something like...

Person.prototype.getName = function() { return this.name; }

All objects created from this constructor will now have a getName because of the prototype chain that they have access to.

Adrian Thompson Phillips
  • 6,278
  • 6
  • 34
  • 61
meder omuraliev
  • 171,706
  • 64
  • 370
  • 423
29

JavaScript is an object-oriented programming language and it's used exactly for creating instances. It's prototype-based, rather than class-based, but that does not mean that it is not object-oriented.

hyperslug
  • 3,103
  • 1
  • 25
  • 28
Michael
  • 8,344
  • 3
  • 35
  • 53
  • 9
    I like to say that JavaScript seems to be even more object-oriented than all those class-based languages. In JavaScript everything you write immediately becomes an object, but in class-based languages you first write declarations and only later you create specific instances (objects) of classes. And JavaScript prototype seems to vaguely remind all that VTABLE stuff for class-based languages. – JustAMartin Oct 07 '13 at 07:33
19

Summary:

The new keyword is used in javascript to create a object from a constructor function. The new keyword has to be placed before the constructor function call and will do the following things:

  1. Creates a new object
  2. Sets the prototype of this object to the constructor function's prototype property
  3. Binds the this keyword to the newly created object and executes the constructor function
  4. Returns the newly created object

Example:

function Dog (age) {
  this.age = age;
}

const doggie = new Dog(12);

console.log(doggie);
console.log(Object.getPrototypeOf(doggie) === Dog.prototype) // true

What exactly happens:

  1. const doggie says: We need memory for declaring a variable.
  2. The assigment operator = says: We are going to initialize this variable with the expression after the =
  3. The expression is new Dog(12). The JS engine sees the new keyword, creates a new object and sets the prototype to Dog.prototype
  4. The constructor function is executed with the this value set to the new object. In this step is where the age is assigned to the new created doggie object.
  5. The newly created object is returned and assigned to the variable doggie.
Willem van der Veen
  • 19,609
  • 11
  • 116
  • 113
16

There are already some very great answers but I'm posting a new one to emphasize my observation on case III below about what happens when you have an explicit return statement in a function which you are newing up. Have a look at below cases:

Case I:

var Foo = function(){
  this.A = 1; 
  this.B = 2;
};
console.log(Foo()); //prints undefined
console.log(window.A); //prints 1

Above is a plain case of calling the anonymous function pointed by Foo. When you call this function it returns undefined. Since there is no explicit return statement so JavaScript interpreter forcefully inserts a return undefined; statement in the end of the function. Here window is the invocation object (contextual this) which gets new A and B properties.

Case II:

var Foo = function(){
  this.A = 1;
  this.B = 2;
};
var bar = new Foo();
console.log(bar()); //illegal isn't pointing to a function but an object
console.log(bar.A); //prints 1

Here JavaScript interpreter seeing the new keyword creates a new object which acts as the invocation object (contextual this) of anonymous function pointed by Foo. In this case A and B become properties on the newly created object (in place of window object). Since you don't have any explicit return statement so JavaScript interpreter forcefully inserts a return statement to return the new object created due to usage of new keyword.

Case III:

var Foo = function(){
  this.A = 1;
  this.B = 2;
  return {C:20,D:30}; 
};
var bar = new Foo();
console.log(bar.C);//prints 20
console.log(bar.A); //prints undefined. bar is not pointing to the object which got created due to new keyword.

Here again JavaScript interpreter seeing the new keyword creates a new object which acts as the invocation object (contextual this) of anonymous function pointed by Foo. Again, A and B become properties on the newly created object. But this time you have an explicit return statement so JavaScript interpreter will not do anything of its own.

The thing to note in case III is that the object being created due to new keyword got lost from your radar. bar is actually pointing to a completely different object which is not the one which JavaScript interpreter created due to new keyword.

Quoting David Flanagan from JavaScripit: The Definitive Guide (6th Edition),Ch. 4, Page # 62:

When an object creation expression is evaluated, JavaScript first creates a new empty object, just like the one created by the object initializer {}. Next, it invokes the specified function with the specified arguments, passing the new object as the value of the this keyword. The function can then use this to initialize the properties of the newly created object. Functions written for use as constructors do not return a value, and the value of the object creation expression is the newly created and initialized object. If a constructor does return an object value, that value becomes the value of the object creation expression and the newly created object is discarded.

---Additional Info---

The functions used in code snippet of above cases have special names in JS world as below:

Case I and II - Constructor function

Case III - Factory function. Factory functions shouldn't be used with new keyword which I've done to explain the concept in current thread.

You can read about difference between them in this thread.

RBT
  • 18,275
  • 13
  • 127
  • 181
14

Javascript is a dynamic programming language which supports the object oriented programming paradigm, and it use used for creating new instances of object.

Classes are not necessary for objects - Javascript is a prototype based language.

Seth
  • 9,056
  • 9
  • 40
  • 67
Greg
  • 295,929
  • 52
  • 357
  • 326
7

sometimes code is easier than words:

var func1 = function (x) { this.x = x; }                    // used with 'new' only
var func2 = function (x) { var z={}; z.x = x; return z; }   // used both ways
func1.prototype.y = 11;
func2.prototype.y = 12;

A1 = new func1(1);      // has A1.x  AND  A1.y
A2 =     func1(1);      // undefined ('this' refers to 'window')
B1 = new func2(2);      // has B1.x  ONLY
B2 =     func2(2);      // has B2.x  ONLY

for me, as long as I not prototype, I use style of func2 as it gives me a bit more flexibility inside and outside the function.

rsbkk
  • 225
  • 3
  • 2
7

The new keyword changes the context under which the function is being run and returns a pointer to that context.

When you don't use the new keyword, the context under which function Vehicle() runs is the same context from which you are calling the Vehicle function. The this keyword will refer to the same context. When you use new Vehicle(), a new context is created so the keyword this inside the function refers to the new context. What you get in return is the newly created context.

Juzer Ali
  • 3,803
  • 2
  • 28
  • 57
5
 " Every object (including functions) has this internal property called [[prototype]]" 

Every function has a proto- type object that’s automatically set as the prototype of the objects created with that function.

you guys can check easily:

const a = { name: "something" };
console.log(a.prototype); // undefined because it is not directly accessible

const b = function () {
  console.log("somethign");};

console.log(b.prototype); // returns b {}

But every function and objects has __proto__ property which points to the prototype of that object or function. __proto__ and prototype are 2 different terms. I think we can make this comment: "Every object is linked to a prototype via the proto " But __proto__ does not exist in javascript. this property is added by browser just to help for debugging.

console.log(a.__proto__); // returns {}
console.log(b.__proto__); // returns [Function]

You guys can check this on the terminal easily. So what is constructor function.

function CreateObject(name,age){
    this.name=name;
    this.age =age
}

5 things that pay attention first:

1- When constructor function is invoked with new, the function’s internal [[Construct]] method is called to create a new instance object and allocate memory.

2- We are not using return keyword. new will handle it.

3- Name of the function is capitalized so when developers see your code they can understand that they have to use new keyword.

4- We do not use arrow function. Because the value of the this parameter is picked up at the moment that the arrow function is created which is "window". arrow functions are lexically scoped, not dynamically. Lexically here means locally. arrow function carries its local "this" value.

5- Unlike regular functions, arrow functions can never be called with the new keyword because they do not have the [[Construct]] method. The prototype property also does not exist for arrow functions.

const me=new CreateObject("yilmaz","21")

new invokes the function and then creates an empty object {} and then adds "name" key with the value of "name", and "age" key with the value of argument "age".

When we invoke a function, a new execution context is created with "this" and "arguments", that is why "new" has access to these arguments.

By default this inside the constructor function will point to the "window" object, but new changes it. "this" points to the empty object {} that is created and then properties are added to newly created object. If you had any variable that defined without "this" property will no be added to the object.

function CreateObject(name,age){
    this.name=name;
    this.age =age;
    const myJob="developer"
}

myJob property will not added to the object because there is nothing referencing to the newly created object.

   const me= {name:"yilmaz",age:21} // there is no myJob key

in the beginning I said every function has "prototype" property including constructor functions. We can add methods to the prototype of the constructor, so every object that created from that function will have access to it.

 CreateObject.prototype.myActions=function(){ //define something}

Now "me" object can use "myActions" method.

javascript has built-in constructor functions: Function,Boolean,Number,String..

if I create

const a = new Number(5);
console.log(a);  // [Number: 5]
console.log(typeof a); // object

Anything that created by using new has type of object. now "a" has access all of the methods that are stored inside Number.prototype. If I defined

const b = 5;
console.log(a === b);//false

a and b are 5 but a is object and b is primitive. even though b is primitive type, when it is created, javascript automatically wraps it with Number(), so b has access to all of the methods that inside Number.prototype.

Constructor function is useful when you want to create multiple similar objects with the same properties and methods. That way you will not be allocating extra memory so your code will run more efficiently.

Yilmaz
  • 4,262
  • 6
  • 24
  • 52
  • abi anlatim guzel tesekkurler +1 ledim de, what is the btw Constructor function and Class in JS? – snr Sep 01 '20 at 16:30
  • I have to write in english otherwise it would be considered as scam :) Class is like a factory. Imagine like a car factory. Each car has its own properties and methods: like color, having 4 wheels, having a motor etc. So the constructor is where you construct the car like a production unit of the factory. Whenever you create a new car, specific attributes of the car will be built in the constructor. for example, not all cars have the same color. so we pass the color when we construct or initiate the car. So each car will have color, so it will be specified in the constructor – Yilmaz Sep 01 '20 at 17:31
  • properties in the constructor will be stored inside the car object or car instance. imagine you construct 1000 car instances, and this will take up too much space. So properties that each car will have in common are specified outside the constructor. For example every car has 4 wheels. so it is stored in the prototype. attributes are stored in prototype, are not stored inside each car object. instead it will be stored in one place and you will use it when it is needed. this is called prototypical inheritance. i hope my explanation is clear enough :) – Yilmaz Sep 01 '20 at 17:35
  • 1
    I like your answer, thanks! – Jacob Ensor Dec 04 '20 at 04:11
3

The new keyword is for creating new object instances. And yes, javascript is a dynamic programming language, which supports the object oriented programming paradigm. The convention about the object naming is, always use capital letter for objects that are supposed to be instantiated by the new keyword.

obj = new Element();
Seth
  • 9,056
  • 9
  • 40
  • 67
erenon
  • 17,952
  • 2
  • 56
  • 83
2

The new keyword creates instances of objects using functions as a constructor. For instance:

var Foo = function() {};
Foo.prototype.bar = 'bar';

var foo = new Foo();
foo instanceof Foo; // true

Instances inherit from the prototype of the constructor function. So given the example above...

foo.bar; // 'bar'
eyelidlessness
  • 58,600
  • 11
  • 86
  • 93
  • 2
    The new keyword basically associates the function as the constructor already; you don't need to return anything. You can just do: function foo(x) { this.bar = x; } var obj = new foo(10); alert(obj.bar); – reko_t Oct 29 '09 at 21:40
  • You need not return objects from constructor function unless you specifically want to, for a purpose. For example, if you have to return a specific object instance instead of creating a new object every time (for whatever reason). In your example, however, it is totally unnecessary. – Chetan S Oct 29 '09 at 21:43
  • Well, it was an example. You *can* return an object. There's many patterns used in this scenario, I provided one as a "for instance", hence my words "for instance". – eyelidlessness Oct 29 '09 at 21:43
1

Well JavaScript per si can differ greatly from platform to platform as it is always an implementation of the original specification EcmaScript.

In any case, independently of the implementation all JavaScript implementations that follow the EcmaScript specification right, will give you an Object Oriented Language. According to the ES standard:

ECMAScript is an object-oriented programming language for performing computations and manipulating computational objects within a host environment.

So now that we have agreed that JavaScript is an implementation of EcmaScript and therefore it is an object-oriented language. The definition of the new operation in any Object-oriented language, says that such keyword is used to create an object instance from a class of a certain type (including anonymous types, in cases like C#).

In EcmaScript we don't use classes, as you can read from the specs:

ECMAScript does not use classes such as those in C++, Smalltalk, or Java. Instead objects may be created in various ways including via a literal notation or via constructors which create objects and then execute code that initializes all or part of them by assigning initial values to their properties. Each constructor is a function that has a property named ― prototype ‖ that is used to implement prototype - based inheritance and shared properties. Objects are created by
using constructors in new expressions; for example, new Date(2009,11) creates a new Date object. Invoking a constructor without using new has consequences that depend on the constructor. For example, Date() produces a string representation of the current date and time rather than an object.

João Pinho
  • 3,460
  • 1
  • 15
  • 27
1

Javascript is not object oriented programming(OOP) language therefore the LOOK UP process in javascript work using 'DELEGATION PROCESS' also known as prototype delegation or prototypical inheritance.

If you try to get the value of a property from an object that it doesn't have, the JavaScript engine looks to the object's prototype (and its prototype, 1 step above at a time) it's prototype chain untll the chain ends upto null which is Object.prototype == null (Standard Object Prototype). At this point if property or method is not defined than undefined is returned.

Thus with the new keyword some of the task that were manually done e.g

  1. Manual Object Creation e.g newObj.
  2. Hidden bond Creation using proto (aka: dunder proto) in JS spec [[prototype]] (i.e. proto)
  3. referencing and assign properties to newObj
  4. return of newObj object.

All is done manually.

function CreateObj(value1, value2) {
  const newObj = {};
  newObj.property1 = value1;
  newObj.property2 = value2;
  return newObj;
}
var obj = CreateObj(10,20);

obj.__proto__ === Object.prototype;              // true
Object.getPrototypeOf(obj) === Object.prototype // true

Javascript Keyword new helps to automate this process:

  1. new object literal is created identified by this:{}
  2. referencing and assign properties to this
  3. Hidden bond Creation [[prototype]] (i.e. proto) to Function.prototype shared space.
  4. implicit return of this object {}
function CreateObj(value1, value2) {
  this.property1 = value1;
  this.property2 = value2;
}

var obj = new CreateObj(10,20);
obj.__proto__ === CreateObj.prototype             // true
Object.getPrototypeOf(obj) == CreateObj.prototype // true

Calling Constructor Function without the new Keyword:

=> this: Window

function CreateObj(value1, value2) {
  var isWindowObj = this === window;
  console.log("Is Pointing to Window Object", isWindowObj);
  this.property1 = value1;
  this.property2 = value2;
}
var obj = new CreateObj(10,20); // Is Pointing to Window Object false
var obj = CreateObj(10,20); // Is Pointing to Window Object true
window.property1; // 10
window.property2; // 20

khizer
  • 444
  • 5
  • 8