Difference between `new function(){this.x=1}` and `{x:1}` - javascript

var Foo = new function(){
this.A = 1;
this.B = 2;
};
var Bar = {
A: 1,
B: 2
};
typeof Foo === "object"
typeof Bar === "object"
What's the difference between the two?
I only found their __proto__ objects to be different:

OK:
var Foo = new function(){
this.A = 1;
this.B = 2;
};
We've got var Foo = new a function — which means that the runtime will invoke that function with this set to a newly-constructed object whose internal prototype link will be set to the value of the "prototype" property of that function. Because that's just an anonymous function instantiated right there in the initialization, its "prototype" property is just a plain empty object, so it really doesn't do anything. The constructor function does initialize two properties of the new object, and that new object is the returned value from the new expression. Thus, Foo is assigned a reference to that constructed object, and the object has a couple of assigned properties. It also has a prototype chain that includes the empty object from the anonymous constructor function, and then after that the prototype inherited from the Object constructor.
In this:
var Bar = {
A: 1,
B: 2
};
we have a variable (Bar) being set to the result of an object initializer expression. That always creates a plain object that inherits only from the Object prototype. The only way that this object is different from the Foo object is that the Foo object has an extra (empty) object in its prototype chain.
So:
Foo will end up being a plain object, not a function.
Bar will also be a plain object, more obviously not a function.
Foo and Bar will be similar but not identical (well, two different objects are never identical, but I mean in terms of their particular characteristics) because Foo has that extra empty object in its prototype chain.

First note it's irrelevant that you omitted the parentheses when calling your anonymous function with new. JSLint will yell at you because it's confusing to do this, but that's what's going on.
I'm pretty sure the internal prototype is the only difference. It may be easier to write this out as it's normally used.
var Car = function() {
this.seats = 4;
};
var car1 = new Car();
var car2 = {
seats: 4
};
Reading this it's clear to me that car1 is an object whose internal prototype is Car - which in your case is an anonymous function not directly held by a variable - and car2 is an object whose internal prototype is Object.

In Javascript all functions are objects. And in your case Foo and Bar are the same, but you can construct the first.
On the same token, I would say that the key insight with constructor functions in this case is that if we have:
function myFoo (){
this.A = 1;
this.B = 2;
};
then
var Foo1 = new myFoo();
the this context is Foo.
var Foo2 = myFoo();
the this is bound to the current context, the window object in this case (meaning you actually have window.A = 1).
See the MDN documentation for a more extensive description.
Function
Constructor
new operator

The first one is a function constructor which outputs a function object (what is assigned to Foo), and the other is just a plain javascript object.

Related

Node.js - calling require caches file - but what if you call 'new'? [duplicate]

This question already has answers here:
How does the new operator work in JavaScript?
(2 answers)
Closed 9 years ago.
I am very confused about how constructors work in JavaScript; despite using the language for several years (mostly as if it were like a semi-imperative version of Lisp) I would like to know more about how objects are supposed to work in it.
Given this code:
function Foo(x) {
return {
bar: function() { return x; }
};
}
What is the difference between calling myFoo = Foo(5) and myFoo = new Foo(5)? Or, in other words, what exactly does a constructor in JavaScript do?
What is the difference between calling myFoo = Foo(5) and myFoo = new Foo(5)?
There's no difference for that code, because it returns an object, and the spec says:
Let result be the result of calling the [[Call]] internal property of F, providing obj as the this value and providing the argument list passed into [[Construct]] as args.
If Type(result) is Object then return result.
Since that function returns a result that is an Object, its result is used. You would notice a difference if it did not return an object, or if it checked this, for example if you rewrote it as:
function Foo(x) {
if (!(this instanceof Foo)) { return new Foo(x); }
this.bar = function() { return x; };
}
// Now instanceof works.
alert((new Foo) instanceof Foo);
What does new in JavaScript do, anyway?
The new operator causes the function to be called with this bound to a newly created Object whose prototype is that function's prototype property.
For user-defined functions,
new f(a, b, c)
is equivalent to
// Create a new instance using f's prototype.
var newInstance = Object.create(f.prototype), result;
// Call the function
result = f.call(newInstance, a, b, c),
// If the result is a non-null object, use it, otherwise use the new instance.
result && typeof result === 'object' ? result : newInstance
Note, that the language specification actually defines functions with two operations, [[Call]] and [[Construct]], so there are some corner cases where new behaves oddly.
For example, bound and built-in functions:
var g = f.call.bind(f);
should define a function that when called, just calls f, so g should be the same as f in all respects, but
new g()
produces
TypeError: function call() { [native code] } is not a constructor
because the builtin function Function.prototype.call supports [[Call]] but not [[Construct]].
Function.prototype.bind also behaves differently around new and regular calls. The this value is always the bound thisValue when called, but is a newly constructed instance when you use new.
In this particular example, there's no difference in the end result.
This is because your Foo function is returning an object instance.
The new operator returns a newly created object that inherits from the constructor's prototype only when the function returns a primitive value (or it doesn't return anything, which is technically the undefined value).
For example:
function Foo () {
return 5; // or "", or null, or no return statement at all (undefined)
}
var foo = new Foo();
typeof foo; // "object"
foo instanceof Foo; // true
Foo.prototype.isPrototypeOf(foo); // true
When you return an object, the newly created object that inherits from the constructor's prototype is simply discarded:
function Foo () {
return {};
}
var foo = new Foo();
typeof foo; // "object"
foo instanceof Foo; // false
Foo.prototype.isPrototypeOf(foo); // false
See also:
What values can a constructor return to avoid returning this?
JavaScript: How does 'new' work internally
In this instance there will not be any difference as you are returning a new object. It could be rewritten as:
function Foo(x){
this._x = x;
}
Foo.prototype.bar = function() {
return this._x;
}
With this syntax, each time you call new Foo, it will create a new object with a property of _x. The benefit is that the bar function will be stored once and reused for multiple instances of Foo. With the code in the question calling Foo() multiple times, it will create a bar function for every instance. So attaching functions to the prototype rather than having them directly on the object will be lighter in memory.
A full breakdown of how the prototype works can be found at MDN.

What's the difference between var p = new Person() and var p = Person()? [duplicate]

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?
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 get or set 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 just `{}`. 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.
Suppose you have this function:
var Foo = function(){
this.A = 1;
this.B = 2;
};
If you call this as a stand-alone 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();
When you add new to a function call, a new object is created (just var bar = new Object()) and 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.
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);
For beginners to understand it better
Try out the following code in the browser console.
function Foo() {
return this;
}
var a = Foo(); // Returns the 'window' object
var b = new Foo(); // Returns an 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 :)
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.
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.
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(Object.getPrototypeOf(doggie) === Dog.prototype) // true
What exactly happens:
const doggie says: We need memory for declaring a variable.
The assignment operator = says: We are going to initialize this variable with the expression after the =
The expression is new Dog(12). The JavaScript 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.
Please take a look at my observation on case III below. It is about what happens when you have an explicit return statement in a function which you are newing up. Have a look at the 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 variable Foo. When you call this function it returns undefined. Since there isn’t any explicit return statement, the JavaScript interpreter forcefully inserts a return undefined; statement at the end of the function. So the above code sample is equivalent to:
var Foo = function(){
this.A = 1;
this.B = 2;
return undefined;
};
console.log(Foo()); //prints undefined
console.log(window.A); //prints 1
When Foo function is invoked window is the default 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 the 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, 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, the 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 the new keyword.
Quoting David Flanagan from JavaScript: The Definitive Guide (6th Edition), Chapter 4, Page # 62:
When an object creation expression is evaluated, JavaScript first
creates a new empty object, just like the one created by the object
initializer {}. Next, it invokes the specified function with the
specified arguments, passing the new object as the value of the this
keyword. The function can then use this to initialize the properties
of the newly created object. Functions written for use as constructors
do not return a value, and the value of the object creation expression
is the newly created and initialized object. If a constructor does
return an object value, that value becomes the value of the object
creation expression and the newly created object is discarded.
Additional information:
The functions used in the code snippet of the above cases have special names in the JavaScript world as below:
Case #
Name
Case I
Constructor function
Case II
Constructor function
Case III
Factory function
You can read about the difference between constructor functions and factory functions in this thread.
Code smell in case III - Factory functions should not be used with the new keyword which I've shown in the code snippet above. I've done so deliberately only to explain the concept.
JavaScript is a dynamic programming language which supports the object-oriented programming paradigm, and it is used for creating new instances of objects.
Classes are not necessary for objects. JavaScript is a prototype-based language.
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.
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 do not prototype, I use the style of func2 as it gives me a bit more flexibility inside and outside the function.
Every function has a prototype object that’s automatically set as the prototype of the objects created with that function.
You guys can check easily:
const a = { name: "something" };
console.log(a.prototype); // 'undefined' because it is not directly accessible
const b = function () {
console.log("somethign");
};
console.log(b.prototype); // Returns b {}
But every function and objects has the __proto__ property which points to the prototype of that object or function. __proto__ and prototype are two different terms. I think we can make this comment: "Every object is linked to a prototype via the proto" But __proto__ does not exist in JavaScript. This property is added by browser just to help for debugging.
console.log(a.__proto__); // Returns {}
console.log(b.__proto__); // Returns [Function]
You guys can check this on the terminal easily. So what is a constructor function?
function CreateObject(name, age) {
this.name = name;
this.age = age
}
Five things that pay attention first:
When the constructor function is invoked with new, the function’s internal [[Construct]] method is called to create a new instance object and allocate memory.
We are not using return keyword. new will handle it.
The name of the function is capitalized, so when developers see your code they can understand that they have to use the new keyword.
We do not use the arrow function. Because the value of the this parameter is picked up at the moment that the arrow function is created which is "window". Arrow functions are lexically scoped, not dynamically. Lexically here means locally. The arrow function carries its local "this" value.
Unlike regular functions, arrow functions can never be called with the new keyword, because they do not have the [[Construct]] method. The prototype property also does not exist for arrow functions.
const me = new CreateObject("yilmaz", "21")
new invokes the function and then creates an empty object {} and then adds "name" key with the value of "name", and "age" key with the value of argument "age".
When we invoke a function, a new execution context is created with "this" and "arguments", and that is why "new" has access to these arguments.
By default, this inside the constructor function will point to the "window" object, but new changes it. "this" points to the empty object {} that is created and then properties are added to newly created object. If you had any variable that defined without "this" property will no be added to the object.
function CreateObject(name, age) {
this.name = name;
this.age = age;
const myJob = "developer"
}
myJob property will not added to the object because there is nothing referencing to the newly created object.
const me = {name: "yilmaz", age: 21} // There isn't any 'myJob' key
In the beginning I said every function has a "prototype" property, including constructor functions. We can add methods to the prototype of the constructor, so every object that created from that function will have access to it.
CreateObject.prototype.myActions = function() { /* Define something */ }
Now "me" object can use the "myActions" method.
JavaScript has built-in constructor functions: Function, Boolean, Number, String, etc.
If I create
const a = new Number(5);
console.log(a); // [Number: 5]
console.log(typeof a); // object
Anything that is created by using new has the type of object. Now "a" has access all of the methods that are stored inside Number.prototype. If I defined
const b = 5;
console.log(a === b); // 'false'
a and b are 5 but a is object and b is primitive. Even though b is primitive type, when it is created, JavaScript automatically wraps it with Number(), so b has access to all of the methods that inside Number.prototype.
A constructor function is useful when you want to create multiple similar objects with the same properties and methods. That way you will not be allocating extra memory so your code will run more efficiently.
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 a capital letter for objects that are supposed to be instantiated by the new keyword.
obj = new Element();
JavaScript is not an object-oriented programming (OOP) language. Therefore the look up process in JavaScript works using a delegation process, also known as prototype delegation or prototypical inheritance.
If you try to get the value of a property from an object that it doesn't have, the JavaScript engine looks to the object's prototype (and its prototype, one step above at a time).
It's prototype chain until the chain ends up to null which is Object.prototype == null (Standard Object Prototype).
At this point, if the property or method is not defined then undefined is returned.
Important! Functions are are first-class objects.
Functions = Function + Objects Combo
FunctionName.prototype = { shared SubObject }
{
// other properties
prototype: {
// shared space which automatically gets [[prototype]] linkage
when "new" keyword is used on creating instance of "Constructor
Function"
}
}
Thus with the new keyword, some of the task that were manually done, e.g.,
Manual object creation, e.g., newObj.
Hidden bond creation using proto (AKA: dunder proto) in the JavaScript specification [[prototype]] (i.e., proto)
referencing and assign properties to newObj
return of the newObj object.
All is done manually.
function CreateObj(value1, value2) {
const newObj = {};
newObj.property1 = value1;
newObj.property2 = value2;
return newObj;
}
var obj = CreateObj(10,20);
obj.__proto__ === Object.prototype; // true
Object.getPrototypeOf(obj) === Object.prototype // true
JavaScript keyword new helps to automate this process:
A new object literal is created identified by this:{}
referencing and assign properties to this
Hidden bond creation [[prototype]] (i.e. proto) to Function.prototype shared space.
implicit return of this object {}
function CreateObj(value1, value2) {
this.property1 = value1;
this.property2 = value2;
}
var obj = new CreateObj(10,20);
obj.__proto__ === CreateObj.prototype // true
Object.getPrototypeOf(obj) == CreateObj.prototype // true
Calling a constructor function without the new keyword:
=> this: Window
function CreateObj(value1, value2) {
var isWindowObj = this === window;
console.log("Is Pointing to Window Object", isWindowObj);
this.property1 = value1;
this.property2 = value2;
}
var obj = new CreateObj(10,20); // Is Pointing to Window Object false
var obj = CreateObj(10,20); // Is Pointing to Window Object true
window.property1; // 10
window.property2; // 20
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'
Well, JavaScript per se can differ greatly from platform to platform as it is always an implementation of the original specification ECMAScript (ES).
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 a 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 specifications:
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.
It has 3 stages:
1.Create: It creates a new object, and sets this object's [[prototype]] property to be the prototype property of the constructor function.
2.Execute: It makes this point to the newly created object and executes the constructor function.
3.Return: In normal case, it will return the newly created object. However, if you explicitly return a non-null object or a function , this value is returned instead. To be mentioned, if you return a non-null value, but it is not an object(such as Symbol value, undefined, NaN), this value is ignored and the newly created object is returned.
function myNew(constructor, ...args) {
const obj = {}
Object.setPrototypeOf(obj, constructor.prototype)
const returnedVal = constructor.apply(obj, args)
if (
typeof returnedVal === 'function'
|| (typeof returnedVal === 'object' && returnedVal !== null)) {
return returnedVal
}
return obj
}
For more info and the tests for myNew, you can read my blog: https://medium.com/#magenta2127/how-does-the-new-operator-work-f7eaac692026

Need help understanding a certain code [duplicate]

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?
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 get or set 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 just `{}`. 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.
Suppose you have this function:
var Foo = function(){
this.A = 1;
this.B = 2;
};
If you call this as a stand-alone 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();
When you add new to a function call, a new object is created (just var bar = new Object()) and 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.
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);
For beginners to understand it better
Try out the following code in the browser console.
function Foo() {
return this;
}
var a = Foo(); // Returns the 'window' object
var b = new Foo(); // Returns an 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 :)
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.
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.
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(Object.getPrototypeOf(doggie) === Dog.prototype) // true
What exactly happens:
const doggie says: We need memory for declaring a variable.
The assignment operator = says: We are going to initialize this variable with the expression after the =
The expression is new Dog(12). The JavaScript 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.
Please take a look at my observation on case III below. It is about what happens when you have an explicit return statement in a function which you are newing up. Have a look at the 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 variable Foo. When you call this function it returns undefined. Since there isn’t any explicit return statement, the JavaScript interpreter forcefully inserts a return undefined; statement at the end of the function. So the above code sample is equivalent to:
var Foo = function(){
this.A = 1;
this.B = 2;
return undefined;
};
console.log(Foo()); //prints undefined
console.log(window.A); //prints 1
When Foo function is invoked window is the default 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 the 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, 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, the 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 the new keyword.
Quoting David Flanagan from JavaScript: The Definitive Guide (6th Edition), Chapter 4, Page # 62:
When an object creation expression is evaluated, JavaScript first
creates a new empty object, just like the one created by the object
initializer {}. Next, it invokes the specified function with the
specified arguments, passing the new object as the value of the this
keyword. The function can then use this to initialize the properties
of the newly created object. Functions written for use as constructors
do not return a value, and the value of the object creation expression
is the newly created and initialized object. If a constructor does
return an object value, that value becomes the value of the object
creation expression and the newly created object is discarded.
Additional information:
The functions used in the code snippet of the above cases have special names in the JavaScript world as below:
Case #
Name
Case I
Constructor function
Case II
Constructor function
Case III
Factory function
You can read about the difference between constructor functions and factory functions in this thread.
Code smell in case III - Factory functions should not be used with the new keyword which I've shown in the code snippet above. I've done so deliberately only to explain the concept.
JavaScript is a dynamic programming language which supports the object-oriented programming paradigm, and it is used for creating new instances of objects.
Classes are not necessary for objects. JavaScript is a prototype-based language.
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.
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 do not prototype, I use the style of func2 as it gives me a bit more flexibility inside and outside the function.
Every function has a prototype object that’s automatically set as the prototype of the objects created with that function.
You guys can check easily:
const a = { name: "something" };
console.log(a.prototype); // 'undefined' because it is not directly accessible
const b = function () {
console.log("somethign");
};
console.log(b.prototype); // Returns b {}
But every function and objects has the __proto__ property which points to the prototype of that object or function. __proto__ and prototype are two different terms. I think we can make this comment: "Every object is linked to a prototype via the proto" But __proto__ does not exist in JavaScript. This property is added by browser just to help for debugging.
console.log(a.__proto__); // Returns {}
console.log(b.__proto__); // Returns [Function]
You guys can check this on the terminal easily. So what is a constructor function?
function CreateObject(name, age) {
this.name = name;
this.age = age
}
Five things that pay attention first:
When the constructor function is invoked with new, the function’s internal [[Construct]] method is called to create a new instance object and allocate memory.
We are not using return keyword. new will handle it.
The name of the function is capitalized, so when developers see your code they can understand that they have to use the new keyword.
We do not use the arrow function. Because the value of the this parameter is picked up at the moment that the arrow function is created which is "window". Arrow functions are lexically scoped, not dynamically. Lexically here means locally. The arrow function carries its local "this" value.
Unlike regular functions, arrow functions can never be called with the new keyword, because they do not have the [[Construct]] method. The prototype property also does not exist for arrow functions.
const me = new CreateObject("yilmaz", "21")
new invokes the function and then creates an empty object {} and then adds "name" key with the value of "name", and "age" key with the value of argument "age".
When we invoke a function, a new execution context is created with "this" and "arguments", and that is why "new" has access to these arguments.
By default, this inside the constructor function will point to the "window" object, but new changes it. "this" points to the empty object {} that is created and then properties are added to newly created object. If you had any variable that defined without "this" property will no be added to the object.
function CreateObject(name, age) {
this.name = name;
this.age = age;
const myJob = "developer"
}
myJob property will not added to the object because there is nothing referencing to the newly created object.
const me = {name: "yilmaz", age: 21} // There isn't any 'myJob' key
In the beginning I said every function has a "prototype" property, including constructor functions. We can add methods to the prototype of the constructor, so every object that created from that function will have access to it.
CreateObject.prototype.myActions = function() { /* Define something */ }
Now "me" object can use the "myActions" method.
JavaScript has built-in constructor functions: Function, Boolean, Number, String, etc.
If I create
const a = new Number(5);
console.log(a); // [Number: 5]
console.log(typeof a); // object
Anything that is created by using new has the type of object. Now "a" has access all of the methods that are stored inside Number.prototype. If I defined
const b = 5;
console.log(a === b); // 'false'
a and b are 5 but a is object and b is primitive. Even though b is primitive type, when it is created, JavaScript automatically wraps it with Number(), so b has access to all of the methods that inside Number.prototype.
A constructor function is useful when you want to create multiple similar objects with the same properties and methods. That way you will not be allocating extra memory so your code will run more efficiently.
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 a capital letter for objects that are supposed to be instantiated by the new keyword.
obj = new Element();
JavaScript is not an object-oriented programming (OOP) language. Therefore the look up process in JavaScript works using a delegation process, also known as prototype delegation or prototypical inheritance.
If you try to get the value of a property from an object that it doesn't have, the JavaScript engine looks to the object's prototype (and its prototype, one step above at a time).
It's prototype chain until the chain ends up to null which is Object.prototype == null (Standard Object Prototype).
At this point, if the property or method is not defined then undefined is returned.
Important! Functions are are first-class objects.
Functions = Function + Objects Combo
FunctionName.prototype = { shared SubObject }
{
// other properties
prototype: {
// shared space which automatically gets [[prototype]] linkage
when "new" keyword is used on creating instance of "Constructor
Function"
}
}
Thus with the new keyword, some of the task that were manually done, e.g.,
Manual object creation, e.g., newObj.
Hidden bond creation using proto (AKA: dunder proto) in the JavaScript specification [[prototype]] (i.e., proto)
referencing and assign properties to newObj
return of the newObj object.
All is done manually.
function CreateObj(value1, value2) {
const newObj = {};
newObj.property1 = value1;
newObj.property2 = value2;
return newObj;
}
var obj = CreateObj(10,20);
obj.__proto__ === Object.prototype; // true
Object.getPrototypeOf(obj) === Object.prototype // true
JavaScript keyword new helps to automate this process:
A new object literal is created identified by this:{}
referencing and assign properties to this
Hidden bond creation [[prototype]] (i.e. proto) to Function.prototype shared space.
implicit return of this object {}
function CreateObj(value1, value2) {
this.property1 = value1;
this.property2 = value2;
}
var obj = new CreateObj(10,20);
obj.__proto__ === CreateObj.prototype // true
Object.getPrototypeOf(obj) == CreateObj.prototype // true
Calling a constructor function without the new keyword:
=> this: Window
function CreateObj(value1, value2) {
var isWindowObj = this === window;
console.log("Is Pointing to Window Object", isWindowObj);
this.property1 = value1;
this.property2 = value2;
}
var obj = new CreateObj(10,20); // Is Pointing to Window Object false
var obj = CreateObj(10,20); // Is Pointing to Window Object true
window.property1; // 10
window.property2; // 20
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'
Well, JavaScript per se can differ greatly from platform to platform as it is always an implementation of the original specification ECMAScript (ES).
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 a 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 specifications:
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.
It has 3 stages:
1.Create: It creates a new object, and sets this object's [[prototype]] property to be the prototype property of the constructor function.
2.Execute: It makes this point to the newly created object and executes the constructor function.
3.Return: In normal case, it will return the newly created object. However, if you explicitly return a non-null object or a function , this value is returned instead. To be mentioned, if you return a non-null value, but it is not an object(such as Symbol value, undefined, NaN), this value is ignored and the newly created object is returned.
function myNew(constructor, ...args) {
const obj = {}
Object.setPrototypeOf(obj, constructor.prototype)
const returnedVal = constructor.apply(obj, args)
if (
typeof returnedVal === 'function'
|| (typeof returnedVal === 'object' && returnedVal !== null)) {
return returnedVal
}
return obj
}
For more info and the tests for myNew, you can read my blog: https://medium.com/#magenta2127/how-does-the-new-operator-work-f7eaac692026

Why is prototype assignment not working here?

var foo = {
name: "foo"
};
var bar = {};
bar.prototype = foo;
document.writeln("Bar name: " + bar.name + "<br />");
And here's what I got in browser:
Bar name: undefined
Why is this happening? Shouldn't Javascript look up name on bar, and then go up on foo and finds it? Why is it simply undefined?
Unfortunately, in Javascript x.prototype != "prototype of x". x.prototype means "if x is a constructor (=function), x.prototype will be a prototype of new x". If x is not a function, x.prototype doesn't make sense.
This is no more and no less confusing than the rest of the language. Remember, Mr. Eich had only 10 days to create it [ref].
To assign a prototype to an already created object, ES6 (Harmony) offers setPrototypeOf. In other engines, there's a vendor-specific hack o.__proto__=.... Mostly, it's a bad idea.
As others already correctly explained, the prototype system doesn't work like that in ECMAscript. You should instead use ECMAscripts Object.create method, which will do the magic for you.
var foo = {
name: "foo"
};
var bar = Object.create( foo );
console.log("Bar name: " + bar.name);
.create() will pretty much do this under the hood:
Object.create = (function(){
function F(){}
return function( o ){
F.prototype = o;
return new F()
}
})();
You can't directly set the prototype property on a plain object.
When you define a (constructor) function you can specify the prototype property of that function, and when that constructor is subsequently invoked the given property will be attached to the prototype chain of the new object.
So this would work:
var foo = { name: "foo" };
function Bar() { ... }
Bar.prototype = foo;
var b = new Bar();
// b.name now exists
However in ES5 you should use Object.create instead.
The prototype property, that is used for inheritance in JavaScript, is a member of the constructor function. It is not a member of the object that is created from the constructor function.
The object that is created from the constructor function has an internal property [[Prototype]] which is the same as the prototype property of the constuctor function. When you access a property on an object and the object does not have that property on its own, the [[Prototype]] object is searched for that property. But the [[Prototype]] property itself is not accessible from the language (it's only there for specification purposes).

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?
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 get or set 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 just `{}`. 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.
Suppose you have this function:
var Foo = function(){
this.A = 1;
this.B = 2;
};
If you call this as a stand-alone 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();
When you add new to a function call, a new object is created (just var bar = new Object()) and 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.
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);
For beginners to understand it better
Try out the following code in the browser console.
function Foo() {
return this;
}
var a = Foo(); // Returns the 'window' object
var b = new Foo(); // Returns an 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 :)
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.
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.
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(Object.getPrototypeOf(doggie) === Dog.prototype) // true
What exactly happens:
const doggie says: We need memory for declaring a variable.
The assignment operator = says: We are going to initialize this variable with the expression after the =
The expression is new Dog(12). The JavaScript 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.
Please take a look at my observation on case III below. It is about what happens when you have an explicit return statement in a function which you are newing up. Have a look at the 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 variable Foo. When you call this function it returns undefined. Since there isn’t any explicit return statement, the JavaScript interpreter forcefully inserts a return undefined; statement at the end of the function. So the above code sample is equivalent to:
var Foo = function(){
this.A = 1;
this.B = 2;
return undefined;
};
console.log(Foo()); //prints undefined
console.log(window.A); //prints 1
When Foo function is invoked window is the default 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 the 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, 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, the 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 the new keyword.
Quoting David Flanagan from JavaScript: The Definitive Guide (6th Edition), Chapter 4, Page # 62:
When an object creation expression is evaluated, JavaScript first
creates a new empty object, just like the one created by the object
initializer {}. Next, it invokes the specified function with the
specified arguments, passing the new object as the value of the this
keyword. The function can then use this to initialize the properties
of the newly created object. Functions written for use as constructors
do not return a value, and the value of the object creation expression
is the newly created and initialized object. If a constructor does
return an object value, that value becomes the value of the object
creation expression and the newly created object is discarded.
Additional information:
The functions used in the code snippet of the above cases have special names in the JavaScript world as below:
Case #
Name
Case I
Constructor function
Case II
Constructor function
Case III
Factory function
You can read about the difference between constructor functions and factory functions in this thread.
Code smell in case III - Factory functions should not be used with the new keyword which I've shown in the code snippet above. I've done so deliberately only to explain the concept.
JavaScript is a dynamic programming language which supports the object-oriented programming paradigm, and it is used for creating new instances of objects.
Classes are not necessary for objects. JavaScript is a prototype-based language.
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.
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 do not prototype, I use the style of func2 as it gives me a bit more flexibility inside and outside the function.
Every function has a prototype object that’s automatically set as the prototype of the objects created with that function.
You guys can check easily:
const a = { name: "something" };
console.log(a.prototype); // 'undefined' because it is not directly accessible
const b = function () {
console.log("somethign");
};
console.log(b.prototype); // Returns b {}
But every function and objects has the __proto__ property which points to the prototype of that object or function. __proto__ and prototype are two different terms. I think we can make this comment: "Every object is linked to a prototype via the proto" But __proto__ does not exist in JavaScript. This property is added by browser just to help for debugging.
console.log(a.__proto__); // Returns {}
console.log(b.__proto__); // Returns [Function]
You guys can check this on the terminal easily. So what is a constructor function?
function CreateObject(name, age) {
this.name = name;
this.age = age
}
Five things that pay attention first:
When the constructor function is invoked with new, the function’s internal [[Construct]] method is called to create a new instance object and allocate memory.
We are not using return keyword. new will handle it.
The name of the function is capitalized, so when developers see your code they can understand that they have to use the new keyword.
We do not use the arrow function. Because the value of the this parameter is picked up at the moment that the arrow function is created which is "window". Arrow functions are lexically scoped, not dynamically. Lexically here means locally. The arrow function carries its local "this" value.
Unlike regular functions, arrow functions can never be called with the new keyword, because they do not have the [[Construct]] method. The prototype property also does not exist for arrow functions.
const me = new CreateObject("yilmaz", "21")
new invokes the function and then creates an empty object {} and then adds "name" key with the value of "name", and "age" key with the value of argument "age".
When we invoke a function, a new execution context is created with "this" and "arguments", and that is why "new" has access to these arguments.
By default, this inside the constructor function will point to the "window" object, but new changes it. "this" points to the empty object {} that is created and then properties are added to newly created object. If you had any variable that defined without "this" property will no be added to the object.
function CreateObject(name, age) {
this.name = name;
this.age = age;
const myJob = "developer"
}
myJob property will not added to the object because there is nothing referencing to the newly created object.
const me = {name: "yilmaz", age: 21} // There isn't any 'myJob' key
In the beginning I said every function has a "prototype" property, including constructor functions. We can add methods to the prototype of the constructor, so every object that created from that function will have access to it.
CreateObject.prototype.myActions = function() { /* Define something */ }
Now "me" object can use the "myActions" method.
JavaScript has built-in constructor functions: Function, Boolean, Number, String, etc.
If I create
const a = new Number(5);
console.log(a); // [Number: 5]
console.log(typeof a); // object
Anything that is created by using new has the type of object. Now "a" has access all of the methods that are stored inside Number.prototype. If I defined
const b = 5;
console.log(a === b); // 'false'
a and b are 5 but a is object and b is primitive. Even though b is primitive type, when it is created, JavaScript automatically wraps it with Number(), so b has access to all of the methods that inside Number.prototype.
A constructor function is useful when you want to create multiple similar objects with the same properties and methods. That way you will not be allocating extra memory so your code will run more efficiently.
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 a capital letter for objects that are supposed to be instantiated by the new keyword.
obj = new Element();
JavaScript is not an object-oriented programming (OOP) language. Therefore the look up process in JavaScript works using a delegation process, also known as prototype delegation or prototypical inheritance.
If you try to get the value of a property from an object that it doesn't have, the JavaScript engine looks to the object's prototype (and its prototype, one step above at a time).
It's prototype chain until the chain ends up to null which is Object.prototype == null (Standard Object Prototype).
At this point, if the property or method is not defined then undefined is returned.
Important! Functions are are first-class objects.
Functions = Function + Objects Combo
FunctionName.prototype = { shared SubObject }
{
// other properties
prototype: {
// shared space which automatically gets [[prototype]] linkage
when "new" keyword is used on creating instance of "Constructor
Function"
}
}
Thus with the new keyword, some of the task that were manually done, e.g.,
Manual object creation, e.g., newObj.
Hidden bond creation using proto (AKA: dunder proto) in the JavaScript specification [[prototype]] (i.e., proto)
referencing and assign properties to newObj
return of the newObj object.
All is done manually.
function CreateObj(value1, value2) {
const newObj = {};
newObj.property1 = value1;
newObj.property2 = value2;
return newObj;
}
var obj = CreateObj(10,20);
obj.__proto__ === Object.prototype; // true
Object.getPrototypeOf(obj) === Object.prototype // true
JavaScript keyword new helps to automate this process:
A new object literal is created identified by this:{}
referencing and assign properties to this
Hidden bond creation [[prototype]] (i.e. proto) to Function.prototype shared space.
implicit return of this object {}
function CreateObj(value1, value2) {
this.property1 = value1;
this.property2 = value2;
}
var obj = new CreateObj(10,20);
obj.__proto__ === CreateObj.prototype // true
Object.getPrototypeOf(obj) == CreateObj.prototype // true
Calling a constructor function without the new keyword:
=> this: Window
function CreateObj(value1, value2) {
var isWindowObj = this === window;
console.log("Is Pointing to Window Object", isWindowObj);
this.property1 = value1;
this.property2 = value2;
}
var obj = new CreateObj(10,20); // Is Pointing to Window Object false
var obj = CreateObj(10,20); // Is Pointing to Window Object true
window.property1; // 10
window.property2; // 20
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'
Well, JavaScript per se can differ greatly from platform to platform as it is always an implementation of the original specification ECMAScript (ES).
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 a 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 specifications:
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.
It has 3 stages:
1.Create: It creates a new object, and sets this object's [[prototype]] property to be the prototype property of the constructor function.
2.Execute: It makes this point to the newly created object and executes the constructor function.
3.Return: In normal case, it will return the newly created object. However, if you explicitly return a non-null object or a function , this value is returned instead. To be mentioned, if you return a non-null value, but it is not an object(such as Symbol value, undefined, NaN), this value is ignored and the newly created object is returned.
function myNew(constructor, ...args) {
const obj = {}
Object.setPrototypeOf(obj, constructor.prototype)
const returnedVal = constructor.apply(obj, args)
if (
typeof returnedVal === 'function'
|| (typeof returnedVal === 'object' && returnedVal !== null)) {
return returnedVal
}
return obj
}
For more info and the tests for myNew, you can read my blog: https://medium.com/#magenta2127/how-does-the-new-operator-work-f7eaac692026

Categories

Resources