What is the 'new' keyword in JavaScript?












1602















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?










share|improve this question




















  • 10





    Also, related thread - stackoverflow.com/questions/383402/…

    – Chetan Sastry
    Oct 29 '09 at 22:04











  • read these examples first folks, developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…

    – Martian2049
    Dec 30 '18 at 17:00


















1602















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?










share|improve this question




















  • 10





    Also, related thread - stackoverflow.com/questions/383402/…

    – Chetan Sastry
    Oct 29 '09 at 22:04











  • read these examples first folks, developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…

    – Martian2049
    Dec 30 '18 at 17:00
















1602












1602








1602


809






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?










share|improve this question
















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?







javascript new-operator






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Jul 25 '15 at 13:42









Bergi

366k58546872




366k58546872










asked Oct 29 '09 at 21:32









Alon GubkinAlon Gubkin

26.6k50165271




26.6k50165271








  • 10





    Also, related thread - stackoverflow.com/questions/383402/…

    – Chetan Sastry
    Oct 29 '09 at 22:04











  • read these examples first folks, developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…

    – Martian2049
    Dec 30 '18 at 17:00
















  • 10





    Also, related thread - stackoverflow.com/questions/383402/…

    – Chetan Sastry
    Oct 29 '09 at 22:04











  • read these examples first folks, developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…

    – Martian2049
    Dec 30 '18 at 17:00










10




10





Also, related thread - stackoverflow.com/questions/383402/…

– Chetan Sastry
Oct 29 '09 at 22:04





Also, related thread - stackoverflow.com/questions/383402/…

– Chetan Sastry
Oct 29 '09 at 22:04













read these examples first folks, developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…

– Martian2049
Dec 30 '18 at 17:00







read these examples first folks, developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…

– Martian2049
Dec 30 '18 at 17:00














14 Answers
14






active

oldest

votes


















1994














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.






share|improve this answer





















  • 44





    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








  • 9





    Question: what happens differently if ObjMaker is defined as a function that returns a value?

    – Jim Blackler
    Feb 27 '12 at 19:05






  • 10





    @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








  • 10





    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 6 '13 at 2:04






  • 6





    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



















366














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.






share|improve this answer





















  • 5





    Depends on execution context. In my case (Qt scripting) it's just a global object.

    – Maxym
    Jan 21 '13 at 13:24






  • 1





    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






  • 1





    @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








  • 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



















152














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);





share|improve this answer





















  • 66





    I found that javascript is easier to understand than english :v

    – damphat
    Oct 20 '13 at 10:11











  • 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 2 '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: jsfiddle.net/Mk42Z

    – basilikum
    Apr 28 '14 at 18:19






  • 2





    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 8 '15 at 21:40











  • @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 8 '15 at 21:53



















93














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 :)






share|improve this answer





















  • 4





    Good answer. Also - leaving out return this; yields the same output.

    – Nelu
    Feb 2 '17 at 21:26








  • 4





    Would be nice to point out why this is happening.

    – Florian Leitgeb
    Oct 23 '17 at 14:49



















33















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.






share|improve this answer





















  • 6





    function constructors are used like classes, there is no class keyword but you can pretty much do the same thing.

    – meder omuraliev
    Oct 29 '09 at 21:37











  • There kindof is a class keyword - class is reserved for future use

    – Greg
    Oct 29 '09 at 21:41






  • 11





    Incidentally that's why you use .className not .class to set a CSS class

    – Greg
    Oct 29 '09 at 21:41






  • 21





    It should be capitalized Person by convention.

    – eomeroff
    Jun 26 '13 at 13:56



















26














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.






share|improve this answer





















  • 6





    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 7 '13 at 7:33





















13














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.






share|improve this answer

































    3














    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.






    share|improve this answer



















    • 3





      B1 = new func2(2); <- Why this will not have B1.y ?

      – sunny_dev
      Nov 17 '15 at 9:37











    • @sunny_dev I'm not a JS expert, but probably because func2 is returning directly a value (z object), instead of working/returning with internal values (this)

      – Eagle
      Dec 19 '16 at 9:05



















    3














    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.






    share|improve this answer































      2














      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();





      share|improve this answer

































        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.







        share|improve this answer































          1














          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.






          share|improve this answer































            0














            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'





            share|improve this answer





















            • 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 Sastry
              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



















            0














            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(doggie.__proto__ === 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.






            share|improve this answer






















              protected by Shankar Damodaran Jan 15 '14 at 18:25



              Thank you for your interest in this question.
              Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).



              Would you like to answer one of these unanswered questions instead?














              14 Answers
              14






              active

              oldest

              votes








              14 Answers
              14






              active

              oldest

              votes









              active

              oldest

              votes






              active

              oldest

              votes









              1994














              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.






              share|improve this answer





















              • 44





                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








              • 9





                Question: what happens differently if ObjMaker is defined as a function that returns a value?

                – Jim Blackler
                Feb 27 '12 at 19:05






              • 10





                @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








              • 10





                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 6 '13 at 2:04






              • 6





                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
















              1994














              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.






              share|improve this answer





















              • 44





                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








              • 9





                Question: what happens differently if ObjMaker is defined as a function that returns a value?

                – Jim Blackler
                Feb 27 '12 at 19:05






              • 10





                @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








              • 10





                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 6 '13 at 2:04






              • 6





                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














              1994












              1994








              1994







              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.






              share|improve this answer















              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.







              share|improve this answer














              share|improve this answer



              share|improve this answer








              edited Dec 25 '18 at 14:57


























              community wiki





              28 revs, 23 users 56%
              Daniel Howard









              • 44





                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








              • 9





                Question: what happens differently if ObjMaker is defined as a function that returns a value?

                – Jim Blackler
                Feb 27 '12 at 19:05






              • 10





                @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








              • 10





                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 6 '13 at 2:04






              • 6





                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














              • 44





                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








              • 9





                Question: what happens differently if ObjMaker is defined as a function that returns a value?

                – Jim Blackler
                Feb 27 '12 at 19:05






              • 10





                @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








              • 10





                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 6 '13 at 2:04






              • 6





                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








              44




              44





              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







              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






              9




              9





              Question: what happens differently if ObjMaker is defined as a function that returns a value?

              – Jim Blackler
              Feb 27 '12 at 19:05





              Question: what happens differently if ObjMaker is defined as a function that returns a value?

              – Jim Blackler
              Feb 27 '12 at 19:05




              10




              10





              @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







              @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






              10




              10





              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 6 '13 at 2:04





              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 6 '13 at 2:04




              6




              6





              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





              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













              366














              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.






              share|improve this answer





















              • 5





                Depends on execution context. In my case (Qt scripting) it's just a global object.

                – Maxym
                Jan 21 '13 at 13:24






              • 1





                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






              • 1





                @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








              • 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
















              366














              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.






              share|improve this answer





















              • 5





                Depends on execution context. In my case (Qt scripting) it's just a global object.

                – Maxym
                Jan 21 '13 at 13:24






              • 1





                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






              • 1





                @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








              • 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














              366












              366








              366







              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.






              share|improve this answer















              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.







              share|improve this answer














              share|improve this answer



              share|improve this answer








              edited Apr 20 '13 at 22:54









              apsillers

              81.5k9161189




              81.5k9161189










              answered Oct 29 '09 at 22:22









              JulianRJulianR

              12.1k34378




              12.1k34378








              • 5





                Depends on execution context. In my case (Qt scripting) it's just a global object.

                – Maxym
                Jan 21 '13 at 13:24






              • 1





                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






              • 1





                @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








              • 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














              • 5





                Depends on execution context. In my case (Qt scripting) it's just a global object.

                – Maxym
                Jan 21 '13 at 13:24






              • 1





                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






              • 1





                @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








              • 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








              5




              5





              Depends on execution context. In my case (Qt scripting) it's just a global object.

              – Maxym
              Jan 21 '13 at 13:24





              Depends on execution context. In my case (Qt scripting) it's just a global object.

              – Maxym
              Jan 21 '13 at 13:24




              1




              1





              will this cause more memory usage?

              – Jürgen Paul
              Jul 24 '13 at 19:20





              will this cause more memory usage?

              – Jürgen Paul
              Jul 24 '13 at 19:20




              2




              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





              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




              1




              1





              @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







              @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






              1




              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 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











              152














              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);





              share|improve this answer





















              • 66





                I found that javascript is easier to understand than english :v

                – damphat
                Oct 20 '13 at 10:11











              • 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 2 '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: jsfiddle.net/Mk42Z

                – basilikum
                Apr 28 '14 at 18:19






              • 2





                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 8 '15 at 21:40











              • @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 8 '15 at 21:53
















              152














              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);





              share|improve this answer





















              • 66





                I found that javascript is easier to understand than english :v

                – damphat
                Oct 20 '13 at 10:11











              • 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 2 '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: jsfiddle.net/Mk42Z

                – basilikum
                Apr 28 '14 at 18:19






              • 2





                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 8 '15 at 21:40











              • @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 8 '15 at 21:53














              152












              152








              152







              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);





              share|improve this answer















              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);






              share|improve this answer














              share|improve this answer



              share|improve this answer








              edited Dec 10 '14 at 12:54

























              answered Jun 20 '13 at 23:46









              basilikumbasilikum

              8,00032746




              8,00032746








              • 66





                I found that javascript is easier to understand than english :v

                – damphat
                Oct 20 '13 at 10:11











              • 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 2 '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: jsfiddle.net/Mk42Z

                – basilikum
                Apr 28 '14 at 18:19






              • 2





                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 8 '15 at 21:40











              • @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 8 '15 at 21:53














              • 66





                I found that javascript is easier to understand than english :v

                – damphat
                Oct 20 '13 at 10:11











              • 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 2 '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: jsfiddle.net/Mk42Z

                – basilikum
                Apr 28 '14 at 18:19






              • 2





                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 8 '15 at 21:40











              • @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 8 '15 at 21:53








              66




              66





              I found that javascript is easier to understand than english :v

              – damphat
              Oct 20 '13 at 10:11





              I found that javascript is easier to understand than english :v

              – damphat
              Oct 20 '13 at 10:11













              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 2 '14 at 11:12





              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 2 '14 at 11:12




              6




              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: jsfiddle.net/Mk42Z

              – basilikum
              Apr 28 '14 at 18:19





              @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: jsfiddle.net/Mk42Z

              – basilikum
              Apr 28 '14 at 18:19




              2




              2





              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 8 '15 at 21:40





              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 8 '15 at 21:40













              @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 8 '15 at 21:53





              @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 8 '15 at 21:53











              93














              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 :)






              share|improve this answer





















              • 4





                Good answer. Also - leaving out return this; yields the same output.

                – Nelu
                Feb 2 '17 at 21:26








              • 4





                Would be nice to point out why this is happening.

                – Florian Leitgeb
                Oct 23 '17 at 14:49
















              93














              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 :)






              share|improve this answer





















              • 4





                Good answer. Also - leaving out return this; yields the same output.

                – Nelu
                Feb 2 '17 at 21:26








              • 4





                Would be nice to point out why this is happening.

                – Florian Leitgeb
                Oct 23 '17 at 14:49














              93












              93








              93







              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 :)






              share|improve this answer















              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 :)







              share|improve this answer














              share|improve this answer



              share|improve this answer








              edited Dec 28 '18 at 14:07

























              answered May 27 '15 at 9:23









              Anulal SAnulal S

              4,31831826




              4,31831826








              • 4





                Good answer. Also - leaving out return this; yields the same output.

                – Nelu
                Feb 2 '17 at 21:26








              • 4





                Would be nice to point out why this is happening.

                – Florian Leitgeb
                Oct 23 '17 at 14:49














              • 4





                Good answer. Also - leaving out return this; yields the same output.

                – Nelu
                Feb 2 '17 at 21:26








              • 4





                Would be nice to point out why this is happening.

                – Florian Leitgeb
                Oct 23 '17 at 14:49








              4




              4





              Good answer. Also - leaving out return this; yields the same output.

              – Nelu
              Feb 2 '17 at 21:26







              Good answer. Also - leaving out return this; yields the same output.

              – Nelu
              Feb 2 '17 at 21:26






              4




              4





              Would be nice to point out why this is happening.

              – Florian Leitgeb
              Oct 23 '17 at 14:49





              Would be nice to point out why this is happening.

              – Florian Leitgeb
              Oct 23 '17 at 14:49











              33















              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.






              share|improve this answer





















              • 6





                function constructors are used like classes, there is no class keyword but you can pretty much do the same thing.

                – meder omuraliev
                Oct 29 '09 at 21:37











              • There kindof is a class keyword - class is reserved for future use

                – Greg
                Oct 29 '09 at 21:41






              • 11





                Incidentally that's why you use .className not .class to set a CSS class

                – Greg
                Oct 29 '09 at 21:41






              • 21





                It should be capitalized Person by convention.

                – eomeroff
                Jun 26 '13 at 13:56
















              33















              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.






              share|improve this answer





















              • 6





                function constructors are used like classes, there is no class keyword but you can pretty much do the same thing.

                – meder omuraliev
                Oct 29 '09 at 21:37











              • There kindof is a class keyword - class is reserved for future use

                – Greg
                Oct 29 '09 at 21:41






              • 11





                Incidentally that's why you use .className not .class to set a CSS class

                – Greg
                Oct 29 '09 at 21:41






              • 21





                It should be capitalized Person by convention.

                – eomeroff
                Jun 26 '13 at 13:56














              33












              33








              33








              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.






              share|improve this answer
















              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.







              share|improve this answer














              share|improve this answer



              share|improve this answer








              edited Jan 6 '16 at 8:49









              Adrian Thompson Phillips

              5,26032654




              5,26032654










              answered Oct 29 '09 at 21:34









              meder omuralievmeder omuraliev

              139k54338410




              139k54338410








              • 6





                function constructors are used like classes, there is no class keyword but you can pretty much do the same thing.

                – meder omuraliev
                Oct 29 '09 at 21:37











              • There kindof is a class keyword - class is reserved for future use

                – Greg
                Oct 29 '09 at 21:41






              • 11





                Incidentally that's why you use .className not .class to set a CSS class

                – Greg
                Oct 29 '09 at 21:41






              • 21





                It should be capitalized Person by convention.

                – eomeroff
                Jun 26 '13 at 13:56














              • 6





                function constructors are used like classes, there is no class keyword but you can pretty much do the same thing.

                – meder omuraliev
                Oct 29 '09 at 21:37











              • There kindof is a class keyword - class is reserved for future use

                – Greg
                Oct 29 '09 at 21:41






              • 11





                Incidentally that's why you use .className not .class to set a CSS class

                – Greg
                Oct 29 '09 at 21:41






              • 21





                It should be capitalized Person by convention.

                – eomeroff
                Jun 26 '13 at 13:56








              6




              6





              function constructors are used like classes, there is no class keyword but you can pretty much do the same thing.

              – meder omuraliev
              Oct 29 '09 at 21:37





              function constructors are used like classes, there is no class keyword but you can pretty much do the same thing.

              – meder omuraliev
              Oct 29 '09 at 21:37













              There kindof is a class keyword - class is reserved for future use

              – Greg
              Oct 29 '09 at 21:41





              There kindof is a class keyword - class is reserved for future use

              – Greg
              Oct 29 '09 at 21:41




              11




              11





              Incidentally that's why you use .className not .class to set a CSS class

              – Greg
              Oct 29 '09 at 21:41





              Incidentally that's why you use .className not .class to set a CSS class

              – Greg
              Oct 29 '09 at 21:41




              21




              21





              It should be capitalized Person by convention.

              – eomeroff
              Jun 26 '13 at 13:56





              It should be capitalized Person by convention.

              – eomeroff
              Jun 26 '13 at 13:56











              26














              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.






              share|improve this answer





















              • 6





                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 7 '13 at 7:33


















              26














              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.






              share|improve this answer





















              • 6





                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 7 '13 at 7:33
















              26












              26








              26







              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.






              share|improve this answer















              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.







              share|improve this answer














              share|improve this answer



              share|improve this answer








              edited Feb 3 '11 at 16:01









              hyperslug

              2,87012028




              2,87012028










              answered Oct 29 '09 at 21:36









              MichaelMichael

              6,59522851




              6,59522851








              • 6





                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 7 '13 at 7:33
















              • 6





                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 7 '13 at 7:33










              6




              6





              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 7 '13 at 7:33







              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 7 '13 at 7:33













              13














              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.






              share|improve this answer






























                13














                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.






                share|improve this answer




























                  13












                  13








                  13







                  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.






                  share|improve this answer















                  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.







                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited Mar 18 '14 at 20:00









                  Seth

                  6,02163058




                  6,02163058










                  answered Oct 29 '09 at 21:37









                  GregGreg

                  254k46338321




                  254k46338321























                      3














                      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.






                      share|improve this answer



















                      • 3





                        B1 = new func2(2); <- Why this will not have B1.y ?

                        – sunny_dev
                        Nov 17 '15 at 9:37











                      • @sunny_dev I'm not a JS expert, but probably because func2 is returning directly a value (z object), instead of working/returning with internal values (this)

                        – Eagle
                        Dec 19 '16 at 9:05
















                      3














                      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.






                      share|improve this answer



















                      • 3





                        B1 = new func2(2); <- Why this will not have B1.y ?

                        – sunny_dev
                        Nov 17 '15 at 9:37











                      • @sunny_dev I'm not a JS expert, but probably because func2 is returning directly a value (z object), instead of working/returning with internal values (this)

                        – Eagle
                        Dec 19 '16 at 9:05














                      3












                      3








                      3







                      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.






                      share|improve this answer













                      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.







                      share|improve this answer












                      share|improve this answer



                      share|improve this answer










                      answered May 16 '15 at 7:21









                      rsbkkrsbkk

                      15512




                      15512








                      • 3





                        B1 = new func2(2); <- Why this will not have B1.y ?

                        – sunny_dev
                        Nov 17 '15 at 9:37











                      • @sunny_dev I'm not a JS expert, but probably because func2 is returning directly a value (z object), instead of working/returning with internal values (this)

                        – Eagle
                        Dec 19 '16 at 9:05














                      • 3





                        B1 = new func2(2); <- Why this will not have B1.y ?

                        – sunny_dev
                        Nov 17 '15 at 9:37











                      • @sunny_dev I'm not a JS expert, but probably because func2 is returning directly a value (z object), instead of working/returning with internal values (this)

                        – Eagle
                        Dec 19 '16 at 9:05








                      3




                      3





                      B1 = new func2(2); <- Why this will not have B1.y ?

                      – sunny_dev
                      Nov 17 '15 at 9:37





                      B1 = new func2(2); <- Why this will not have B1.y ?

                      – sunny_dev
                      Nov 17 '15 at 9:37













                      @sunny_dev I'm not a JS expert, but probably because func2 is returning directly a value (z object), instead of working/returning with internal values (this)

                      – Eagle
                      Dec 19 '16 at 9:05





                      @sunny_dev I'm not a JS expert, but probably because func2 is returning directly a value (z object), instead of working/returning with internal values (this)

                      – Eagle
                      Dec 19 '16 at 9:05











                      3














                      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.






                      share|improve this answer




























                        3














                        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.






                        share|improve this answer


























                          3












                          3








                          3







                          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.






                          share|improve this answer













                          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.







                          share|improve this answer












                          share|improve this answer



                          share|improve this answer










                          answered Oct 5 '17 at 2:28









                          RBTRBT

                          8,74566895




                          8,74566895























                              2














                              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();





                              share|improve this answer






























                                2














                                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();





                                share|improve this answer




























                                  2












                                  2








                                  2







                                  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();





                                  share|improve this answer















                                  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();






                                  share|improve this answer














                                  share|improve this answer



                                  share|improve this answer








                                  edited Mar 18 '14 at 19:59









                                  Seth

                                  6,02163058




                                  6,02163058










                                  answered Oct 29 '09 at 21:38









                                  erenonerenon

                                  14.4k24576




                                  14.4k24576























                                      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.







                                      share|improve this answer




























                                        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.







                                        share|improve this answer


























                                          1












                                          1








                                          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.







                                          share|improve this answer













                                          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.








                                          share|improve this answer












                                          share|improve this answer



                                          share|improve this answer










                                          answered May 13 '15 at 23:05









                                          João PinhoJoão Pinho

                                          3,11911126




                                          3,11911126























                                              1














                                              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.






                                              share|improve this answer




























                                                1














                                                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.






                                                share|improve this answer


























                                                  1












                                                  1








                                                  1







                                                  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.






                                                  share|improve this answer













                                                  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.







                                                  share|improve this answer












                                                  share|improve this answer



                                                  share|improve this answer










                                                  answered Nov 27 '17 at 13:13









                                                  Juzer AliJuzer Ali

                                                  2,7412254




                                                  2,7412254























                                                      0














                                                      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'





                                                      share|improve this answer





















                                                      • 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 Sastry
                                                        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
















                                                      0














                                                      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'





                                                      share|improve this answer





















                                                      • 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 Sastry
                                                        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














                                                      0












                                                      0








                                                      0







                                                      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'





                                                      share|improve this answer















                                                      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'






                                                      share|improve this answer














                                                      share|improve this answer



                                                      share|improve this answer








                                                      edited Jun 30 '14 at 21:36

























                                                      answered Oct 29 '09 at 21:37









                                                      eyelidlessnesseyelidlessness

                                                      50.3k118190




                                                      50.3k118190








                                                      • 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 Sastry
                                                        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














                                                      • 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 Sastry
                                                        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








                                                      2




                                                      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





                                                      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 Sastry
                                                      Oct 29 '09 at 21:43





                                                      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 Sastry
                                                      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





                                                      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











                                                      0














                                                      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(doggie.__proto__ === 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.






                                                      share|improve this answer




























                                                        0














                                                        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(doggie.__proto__ === 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.






                                                        share|improve this answer


























                                                          0












                                                          0








                                                          0







                                                          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(doggie.__proto__ === 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.






                                                          share|improve this answer













                                                          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(doggie.__proto__ === 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.






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

                                                          const doggie = new Dog(12);

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





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

                                                          const doggie = new Dog(12);

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






                                                          share|improve this answer












                                                          share|improve this answer



                                                          share|improve this answer










                                                          answered Aug 31 '18 at 8:22









                                                          Willem van der VeenWillem van der Veen

                                                          4,36632024




                                                          4,36632024

















                                                              protected by Shankar Damodaran Jan 15 '14 at 18:25



                                                              Thank you for your interest in this question.
                                                              Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).



                                                              Would you like to answer one of these unanswered questions instead?



                                                              Popular posts from this blog

                                                              Berounka

                                                              Sphinx de Gizeh

                                                              Different font size/position of beamer's navigation symbols template's content depending on regular/plain...