Does a function declaration create an object in Javascript? - javascript

Function constructors are able to create objects in javascript but
I have a more basic question.
Declaring a plain function in Javascript using a "function declaration" such as
function Foo()
{
this.prop1 = 20;
//some code
}
Does this create an object internally in javascript heap with pointer as abc and prop1 as 20?
Or is it that the objects are created only when the function constructor is called
like
var a = new Foo() //This definately creates a new object

In javascript, all functions are objects.
You can do things like this:
function foo() {
return true;
}
foo.greeting = "hello";
foo.tone = "mean";
foo.talk = function() {
alert(foo.greeting);
}
foo.talk();
A function object has all the same capabilities as a normal javascript object, but it can also do some additional things such as be used as a constructor and it has a few built-in properties. See the MDN page on Function objects for a description of the other properties/methods it has.

The function declaration only creates function object Foo, but it does not call the function or create an instance of it.
An instance is only created when you actually call the function with new and until then, the property you assign to this does not exist anywhere.
It could also very well be that Foo is never called as a constructor function. Just by looking at a function, you cannot know for certain whether a function is used as a constructor function or not.

Let's go through the execution line by line, adding line 8 for a better understanding:
/* 1 */ function Foo()
/* 2 */ {
/* 3 */ this.prop1 = 20;
/* 4 */ //some code
/* 5 */ }
/* 6 */
/* 7 */ var a = new Foo()
/* 8 */ var b = Foo()
Line 1 executes, the heap now contains one element, a function object named Foo. At this point, Foo hasn't executed. Lines 2 through 5 aren't executed at this point but are used as the body of Foo. Since Foo hasn't been called, line 3 hasn't been called on any object so nothing has a prop1.
Line 7 executes, the interpreter does several things:
It adds a new object to the heap.
It gives this object the prototype chain of Foo. This does nothing special in the case of Foo since we haven't assigned anything to Foo's prototype, but Foo inherits from Object, so the object now has methods like hasOwnProperty and toString.
The interpreter calls Foo passing the newly created object as this.
Line 3 gets executed, assigning 20 the property named prop1. Whether this creates a new object in the physical heap or if it gets assigned to a primitive section of the object really depends on how the interpretter optimizes everything. I'm sure V8 avoids adding an object to the heap.
The new object gets assigned to a in the variable scope of a.
So basically, creating a function adds the function loader to the heap (or possibly stack depending on scope and optimizations), and executing new Foo adds a new object to the stack.
But what if we didn't use new?
For fun, lets see the different behavior when we don't use new. When line 8 executes, since we aren't calling new we perform a normal function call and don't create a new object. The following happens:
We call Foo on line one. Since we aren't in strict mode, this is assigned to the global window object.
Line 3 executes, assigning window.prop1 = 20.
The function returns undefined.
b is set to undefined.

Javascript is a little bit confusing because a function is both a normal function with no/default context, but paired up with new it creates a new object. So
function Foo() {
this.prop1 = 20;
}
console.log( typeof(Foo) ); //-> 'function'
creates an object called Foo which is of type function. Now we can take our function objects and create new objects that will be added to the current stack:
var bar = new Foo();
console.log( typeof(bar) ); // -> 'object' with a pointer named prop1 to 20
Now we have 2 objects, Foo and bar which references an object that was created using Foo as a constructor with new. So new is basically magic and is one of the three ways of creating objects in Javascript. The three ways are:
var object = {}; // Creates an object using object literal notation
new Foo(); // Creates an object with built in 'new'
Object.create(null); // new ECMA5 notation that avoid using new

Related

Javascript constructor return values [duplicate]

This question already has answers here:
What values can a constructor return to avoid returning this?
(6 answers)
Closed 7 years ago.
Consider the following code:
function Foo() {
return "something";
}
var foo = new Foo();
According to the experts in JavaScript, they say that return "nothing" or just "this" from a constructor. Whats the reason for this?
I am aware that when used "new", the "this" would be set to the prototype object of the constructor but not able to understand this point alone.
That particular code will throw a ReferenceError because something is not declared.
You should either return this or have no return statement at all in a constructor function because otherwise you will have constructed a new instance of the class (the value of this, and the default return value) and then thrown it away.
I am aware that when used "new", the "this" would be set to the prototype object of the constructor
Incorrect. It will be set to an instance of the constructor.
When the code new Foo(...) is executed, the following things happen:
1- A new object is created, inheriting from Foo.prototype.
2- The constructor function Foo is called with the specified arguments and this bound to the newly created object. new Foo is equivalent to new Foo(), i.e. if no argument list is specified, Foo is called without arguments.
3- The object returned by the constructor function becomes the result of the whole new expression. If the constructor function doesn't explicitly return an object, the object created in step 1 is used instead. (Normally constructors don't return a value, but they can choose to do so if they want to override the normal object creation process.)
function Car() {}
car1 = new Car();
console.log(car1.color); // undefined
Car.prototype.color = null;
console.log(car1.color); // null
car1.color = "black";
console.log(car1.color); // black
You can find a complete description Here

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

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

Why in JavaScript is a function considered both a constructor and an object?

I have been doing a lot of research on this lately, but have yet to get a really good solid answer. I read somewhere that a new Function() object is created when the JavaScript engine comes across a function statement, which would lead me to believe it could be a child of an object (thus becoming one). So I emailed Douglas Crockford, and his answer was:
Not exactly, because a function
statement does not call the compiler.
But it produces a similar result.
Also, to my knowledge, you can't call members on a function constructor unless it has been instantiated as a new object. So this will not work:
function myFunction(){
this.myProperty = "Am I an object!";
}
myFunction.myProperty; // myFunction is not a function
myFunction().myProperty; // myFunction has no properties
However, this will work:
function myFunction(){
this.myProperty = "Am I an object!";
}
var myFunctionVar = new myFunction();
myFunctionVar.myProperty;
Is this just a matter of semantics... in the whole of the programming world, when does an object really become an object, and how does that map to JavaScript?
There is nothing magical about functions and constructors. All objects in JavaScript are … well, objects. But some objects are more special than the others: namely built-in objects. The difference lies mostly in following aspects:
General treatment of objects. Examples:
Numbers and Strings are immutable (⇒ constants). No methods are defined to change them internally — new objects are always produced as the result. While they have some innate methods, you cannot change them, or add new methods. Any attempts to do so will be ignored.
null and undefined are special objects. Any attempt to use a method on these objects or define new methods causes an exception.
Applicable operators. JavaScript doesn't allow to (re)define operators, so we stuck with what's available.
Numbers have a special way with arithmetic operators: +, -, *, /.
Strings have a special way to handle the concatenation operator: +.
Functions have a special way to handle the "call" operator: (), and the new operator. The latter has the innate knowledge on how to use the prototype property of the constructor, construct an object with proper internal links to the prototype, and call the constructor function on it setting up this correctly.
If you look into the ECMAScript standard (PDF) you will see that all these "extra" functionality is defined as methods and properties, but many of them are not available to programmers directly. Some of them will be exposed in the new revision of the standard ES3.1 (draft as of 15 Dec 2008: PDF). One property (__proto__) is already exposed in Firefox.
Now we can answer your question directly. Yes, a function object has properties, and we can add/remove them at will:
var fun = function(){/* ... */};
fun.foo = 2;
console.log(fun.foo); // 2
fun.bar = "Ha!";
console.log(fun.bar); // Ha!
It really doesn't matter what the function actually does — it never comes to play because we don't call it! Now let's define it:
fun = function(){ this.life = 42; };
By itself it is not a constructor, it is a function that operates on its context. And we can easily provide it:
var context = {ford: "perfect"};
// now let's call our function on our context
fun.call(context);
// it didn't create new object, it modified the context:
console.log(context.ford); // perfect
console.log(context.life); // 42
console.log(context instanceof fun); // false
As you can see it added one more property to the already existing object.
In order to use our function as a constructor we have to use the new operator:
var baz = new fun();
// new empty object was created, and fun() was executed on it:
console.log(baz.life); // 42
console.log(baz instanceof fun); // true
As you can see new made our function a constructor. Following actions were done by new:
New empty object ({}) was created.
Its internal prototype property was set to fun.prototype. In our case it will be an empty object ({}) because we didn't modify it in any way.
fun() was called with this new object as a context.
It is up to our function to modify the new object. Commonly it sets up properties of the object, but it can do whatever it likes.
Fun trivia:
Because the constructor is just an object we can calculate it:
var A = function(val){ this.a = val; };
var B = function(val){ this.b = val; };
var C = function(flag){ return flag ? A : B; };
// now let's create an object:
var x = new (C(true))(42);
// what kind of object is that?
console.log(x instanceof C); // false
console.log(x instanceof B); // false
console.log(x instanceof A); // true
// it is of A
// let's inspect it
console.log(x.a); // 42
console.log(x.b); // undefined
// now let's create another object:
var y = new (C(false))(33);
// what kind of object is that?
console.log(y instanceof C); // false
console.log(y instanceof B); // true
console.log(y instanceof A); // false
// it is of B
// let's inspect it
console.log(y.a); // undefined
console.log(y.b); // 33
// cool, heh?
Constructor can return a value overriding the newly created object:
var A = function(flag){
if(flag){
// let's return something completely different
return {ford: "perfect"};
}
// let's modify the object
this.life = 42;
};
// now let's create two objects:
var x = new A(false);
var y = new A(true);
// let's inspect x
console.log(x instanceof A); // true
console.log(x.ford); // undefined
console.log(x.life); // 42
// let's inspect y
console.log(y instanceof A); // false
console.log(y.ford); // perfect
console.log(y.life); // undefined
As you can see x is of A with the prototype and all, while y is our "naked" object we returned from the constructor.
Your understanding is wrong:
myFunction().myProperty; // myFunction has no properties
The reason it does not work is because ".myProperty" is applied to the returned value of "myFunction()", not to the object "myFunction". To wit:
$ js
js> function a() { this.b=1;return {b: 2};}
js> a().b
2
js>
Remember, "()" is an operator. "myFunction" is not the same as "myFunction()". You don't need a "return" when instanciang with new:
js> function a() { this.b=1;}
js> d = new a();
[object Object]
js> d.b;
1
To answer your specific question, technically functions are always objects.
For instance, you can always do this:
function foo(){
return 0;
}
foo.bar = 1;
alert(foo.bar); // shows "1"
Javascript functions behave somewhat like classes in other OOP languages when they make use of the this pointer. They can be instantiated as objects with the new keyword:
function Foo(){
this.bar = 1;
}
var foo = new Foo();
alert(foo.bar); // shows "1"
Now this mapping from other OOP languages to Javascript will fail quickly. For instance, there is actually no such thing as classes in Javascript - objects use a prototype chain for inheritance instead.
if you're going to do any sort of significant programming in Javascript, I highly recommend Javascript: The Good Parts by Crockford, that guy you emailed.
The "global" scope of Javascript (at least in a browser) is the window object.
This means that when you do this.myProperty = "foo" and call the function as plain myFunction() you're actually setting window.myProperty = "foo"
The second point with myFunction().myProperty is that here you're looking at the return value of myFunction(), so naturally that won't have any properties as it returns null.
What you're thinking of is this:
function myFunction()
{
myFunction.myProperty = "foo";
}
myFunction();
alert(myFunction.myProperty); // Alerts foo as expected
This is (almost) the same as
var myFunction = new Function('myFunction.myProperty = "foo";');
myFunction();
When you use it in the new context, then the "return value" is your new object and the "this" pointer changes to be your new object, so this works as you expect.
Indeed, Functions are 'first class citizens': they are an Object.
Every object has a Prototype, but only a function's prototype can be referenced directly. When new is called with a function object as argument, a new object is constructed using the function object's prototype as prototype, and this is set to the new object before the function is entered.
So you could call every function a Constructor, even if it leaves this alone.
There are very good tutorials out there on constructors, prototypes etc... Personally I learned a lot from Object Oriented Programming in JavaScript. It shows the equivalence of a function which 'inherits' its prototype, but uses this to fill in a new object's properties, and a function object that uses a specific prototype:
function newA() { this.prop1 = "one"; } // constructs a function object called newA
function newA_Too() {} // constructs a function object called newA_Too
newA_Too.prototype.prop1 = "one";
var A1 = new newA();
var A2 = new newA_Too();
// here A1 equals A2.
First, JavaScript doesn't behave the same way about objects as C++/Java does, so you need to throw those sorts of ideas out of the window to be able to understand how javascript works.
When this line executes:
var myFunctionVar = new myFunction();
then the this inside of myFunction() refers to this new object you are creating - myFunctionVar. Thus this line of code:
this.myProperty = "Am I an object!";
essentially has the result of
myFunctionVar.myProperty = "Am I an object!";
It might help you to take a look at some documentation on the new operator. In JS, the new operator essentially allows you to create an object out of a function - any plain old function. There is nothing special about the function that you use with the new operator that marks it as a constructor, as it would be in C++ or Java. As the documentation says:
Creating a user-defined object type requires two steps:
Define the object type by writing a function.
Create an instance of the object with new.
So what you have done with the code
function myFunction(){
this.myProperty = "Am I an object!";
}
is to create a function that would be useful as a constructor. The reason why the code myFunction.myProperty fails is that there is no reference named myFunction.
JavaScript is based on the ECMA script. Its specification uses the prototyping model for it to be OOP. How ever, ECMA script does not enforce strict data types.
The object needs to be instantiated for the same reason that ECMA script requires a 'new' call which will allocate memory for the property, Otherwise it will remain a function and you can call it if you like, in which case, the property will initialize and then be destroyed when the function ends.
Only when you instantiate with the new keyword does the function act as a constructor.
The result is an object that can use the "this" keyword to access member properties. The this keyword in the method does not make any sense when the function is used any other way.

Categories

Resources