What is the 'new' keyword in JavaScript?
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
add a comment |
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
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
add a comment |
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
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
javascript new-operator
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
add a comment |
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
add a comment |
14 Answers
14
active
oldest
votes
It does 5 things:
- It creates a new object. The type of this object is simply object.
- 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).
- It makes the
this
variable point to the newly created object. - It executes the constructor function, using the newly created object whenever
this
is mentioned. - 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.
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 ifObjMaker
is defined as a function that returns a value?
– Jim Blackler
Feb 27 '12 at 19:05
10
@LonelyPixelnew
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 internalprototype
of the new object to opaquely encapsulate the inherited members, mimicking classical OO inheritance chains (which aren't runtime modifiable). You can simulate this withoutnew
, 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 saysNotice 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
|
show 24 more comments
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.
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 ofwindow
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 expressionwindow
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
|
show 5 more comments
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);
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 forfunc.prototype
to benull
? 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 writingA.prototype = null;
In that casenew A()
will result in on object, thats internal prototype points to theObject
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 preferObject(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, thetypeof
test just makes it easier to understand what is going on behind the scenes.
– basilikum
Oct 8 '15 at 21:53
add a comment |
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 :)
4
Good answer. Also - leaving outreturn 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
add a comment |
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.
6
function constructors are used like classes, there is noclass
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
add a comment |
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.
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
add a comment |
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.
add a comment |
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.
3
B1 = new func2(2);
<- Why this will not haveB1.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
add a comment |
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 new
ing 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.
add a comment |
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();
add a comment |
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.
add a comment |
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.
add a comment |
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'
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
add a comment |
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:
- Creates a new object
- Sets the prototype of this object to the constructor function's prototype property
- Binds the
this
keyword to the newly created object and executes the constructor function - 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:
const doggie
says: We need memory for declaring a variable.- The assigment operator
=
says: We are going to initialize this variable with the expression after the=
- The expression is
new Dog(12)
. The JS engine sees the new keyword, creates a new object and sets the prototype to Dog.prototype - 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. - The newly created object is returned and assigned to the variable doggie.
add a comment |
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
It does 5 things:
- It creates a new object. The type of this object is simply object.
- 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).
- It makes the
this
variable point to the newly created object. - It executes the constructor function, using the newly created object whenever
this
is mentioned. - 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.
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 ifObjMaker
is defined as a function that returns a value?
– Jim Blackler
Feb 27 '12 at 19:05
10
@LonelyPixelnew
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 internalprototype
of the new object to opaquely encapsulate the inherited members, mimicking classical OO inheritance chains (which aren't runtime modifiable). You can simulate this withoutnew
, 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 saysNotice 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
|
show 24 more comments
It does 5 things:
- It creates a new object. The type of this object is simply object.
- 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).
- It makes the
this
variable point to the newly created object. - It executes the constructor function, using the newly created object whenever
this
is mentioned. - 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.
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 ifObjMaker
is defined as a function that returns a value?
– Jim Blackler
Feb 27 '12 at 19:05
10
@LonelyPixelnew
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 internalprototype
of the new object to opaquely encapsulate the inherited members, mimicking classical OO inheritance chains (which aren't runtime modifiable). You can simulate this withoutnew
, 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 saysNotice 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
|
show 24 more comments
It does 5 things:
- It creates a new object. The type of this object is simply object.
- 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).
- It makes the
this
variable point to the newly created object. - It executes the constructor function, using the newly created object whenever
this
is mentioned. - 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.
It does 5 things:
- It creates a new object. The type of this object is simply object.
- 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).
- It makes the
this
variable point to the newly created object. - It executes the constructor function, using the newly created object whenever
this
is mentioned. - 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.
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 ifObjMaker
is defined as a function that returns a value?
– Jim Blackler
Feb 27 '12 at 19:05
10
@LonelyPixelnew
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 internalprototype
of the new object to opaquely encapsulate the inherited members, mimicking classical OO inheritance chains (which aren't runtime modifiable). You can simulate this withoutnew
, 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 saysNotice 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
|
show 24 more comments
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 ifObjMaker
is defined as a function that returns a value?
– Jim Blackler
Feb 27 '12 at 19:05
10
@LonelyPixelnew
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 internalprototype
of the new object to opaquely encapsulate the inherited members, mimicking classical OO inheritance chains (which aren't runtime modifiable). You can simulate this withoutnew
, 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 saysNotice 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
|
show 24 more comments
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.
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 ofwindow
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 expressionwindow
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
|
show 5 more comments
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.
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 ofwindow
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 expressionwindow
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
|
show 5 more comments
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.
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.
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 ofwindow
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 expressionwindow
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
|
show 5 more comments
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 ofwindow
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 expressionwindow
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
|
show 5 more comments
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);
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 forfunc.prototype
to benull
? 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 writingA.prototype = null;
In that casenew A()
will result in on object, thats internal prototype points to theObject
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 preferObject(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, thetypeof
test just makes it easier to understand what is going on behind the scenes.
– basilikum
Oct 8 '15 at 21:53
add a comment |
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);
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 forfunc.prototype
to benull
? 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 writingA.prototype = null;
In that casenew A()
will result in on object, thats internal prototype points to theObject
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 preferObject(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, thetypeof
test just makes it easier to understand what is going on behind the scenes.
– basilikum
Oct 8 '15 at 21:53
add a comment |
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);
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);
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 forfunc.prototype
to benull
? 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 writingA.prototype = null;
In that casenew A()
will result in on object, thats internal prototype points to theObject
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 preferObject(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, thetypeof
test just makes it easier to understand what is going on behind the scenes.
– basilikum
Oct 8 '15 at 21:53
add a comment |
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 forfunc.prototype
to benull
? 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 writingA.prototype = null;
In that casenew A()
will result in on object, thats internal prototype points to theObject
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 preferObject(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, thetypeof
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
add a comment |
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 :)
4
Good answer. Also - leaving outreturn 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
add a comment |
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 :)
4
Good answer. Also - leaving outreturn 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
add a comment |
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 :)
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 :)
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 outreturn 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
add a comment |
4
Good answer. Also - leaving outreturn 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
add a comment |
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.
6
function constructors are used like classes, there is noclass
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
add a comment |
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.
6
function constructors are used like classes, there is noclass
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
add a comment |
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.
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.
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 noclass
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
add a comment |
6
function constructors are used like classes, there is noclass
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
add a comment |
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.
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
add a comment |
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.
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
add a comment |
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.
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.
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
add a comment |
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
add a comment |
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.
add a comment |
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.
add a comment |
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.
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.
edited Mar 18 '14 at 20:00
Seth
6,02163058
6,02163058
answered Oct 29 '09 at 21:37
GregGreg
254k46338321
254k46338321
add a comment |
add a comment |
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.
3
B1 = new func2(2);
<- Why this will not haveB1.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
add a comment |
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.
3
B1 = new func2(2);
<- Why this will not haveB1.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
add a comment |
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.
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.
answered May 16 '15 at 7:21
rsbkkrsbkk
15512
15512
3
B1 = new func2(2);
<- Why this will not haveB1.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
add a comment |
3
B1 = new func2(2);
<- Why this will not haveB1.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
add a comment |
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 new
ing 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.
add a comment |
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 new
ing 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.
add a comment |
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 new
ing 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.
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 new
ing 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.
answered Oct 5 '17 at 2:28
RBTRBT
8,74566895
8,74566895
add a comment |
add a comment |
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();
add a comment |
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();
add a comment |
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();
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();
edited Mar 18 '14 at 19:59
Seth
6,02163058
6,02163058
answered Oct 29 '09 at 21:38
erenonerenon
14.4k24576
14.4k24576
add a comment |
add a comment |
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.
add a comment |
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.
add a comment |
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.
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.
answered May 13 '15 at 23:05
João PinhoJoão Pinho
3,11911126
3,11911126
add a comment |
add a comment |
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.
add a comment |
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.
add a comment |
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.
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.
answered Nov 27 '17 at 13:13
Juzer AliJuzer Ali
2,7412254
2,7412254
add a comment |
add a comment |
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'
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
add a comment |
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'
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
add a comment |
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'
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'
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
add a comment |
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
add a comment |
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:
- Creates a new object
- Sets the prototype of this object to the constructor function's prototype property
- Binds the
this
keyword to the newly created object and executes the constructor function - 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:
const doggie
says: We need memory for declaring a variable.- The assigment operator
=
says: We are going to initialize this variable with the expression after the=
- The expression is
new Dog(12)
. The JS engine sees the new keyword, creates a new object and sets the prototype to Dog.prototype - 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. - The newly created object is returned and assigned to the variable doggie.
add a comment |
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:
- Creates a new object
- Sets the prototype of this object to the constructor function's prototype property
- Binds the
this
keyword to the newly created object and executes the constructor function - 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:
const doggie
says: We need memory for declaring a variable.- The assigment operator
=
says: We are going to initialize this variable with the expression after the=
- The expression is
new Dog(12)
. The JS engine sees the new keyword, creates a new object and sets the prototype to Dog.prototype - 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. - The newly created object is returned and assigned to the variable doggie.
add a comment |
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:
- Creates a new object
- Sets the prototype of this object to the constructor function's prototype property
- Binds the
this
keyword to the newly created object and executes the constructor function - 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:
const doggie
says: We need memory for declaring a variable.- The assigment operator
=
says: We are going to initialize this variable with the expression after the=
- The expression is
new Dog(12)
. The JS engine sees the new keyword, creates a new object and sets the prototype to Dog.prototype - 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. - The newly created object is returned and assigned to the variable doggie.
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:
- Creates a new object
- Sets the prototype of this object to the constructor function's prototype property
- Binds the
this
keyword to the newly created object and executes the constructor function - 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:
const doggie
says: We need memory for declaring a variable.- The assigment operator
=
says: We are going to initialize this variable with the expression after the=
- The expression is
new Dog(12)
. The JS engine sees the new keyword, creates a new object and sets the prototype to Dog.prototype - 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. - 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
answered Aug 31 '18 at 8:22
Willem van der VeenWillem van der Veen
4,36632024
4,36632024
add a comment |
add a comment |
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?
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