Javascript constructor return values [duplicate] - javascript

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

Related

If 'new' is used to instantiate an object with a factory function does it change anything?

In the test code below I use a factory function to instantiate a new object in the traditional way without the new keyword. It works as expected.
function testThis(x) {
let middleStep = {
firstNumber: x.firstNumber,
secondNumber: x.secondNumber
}
return middleStep;
}
let newObject = testThis({firstNumber: 'ONE', secondNumber: 'TWO'});
// new keyword not used
console.log(newObject.firstNumber);
In the next example I use the same method but include the new keyword. It produces the same output and on the surface it seems to work the same way. Does the new keyword change anything when used in this context or is the result the same?
function testThis(x) {
let middleStep = {
firstNumber: x.firstNumber,
secondNumber: x.secondNumber
}
return middleStep;
}
let newObject = new testThis({firstNumber: 'ONE', secondNumber: 'TWO'});
// new keyword included
console.log(newObject.firstNumber);
If the function returns an object, calling it with new will be redundant and equivalent to calling it without new. From MDN:
When the code new Foo(...) is executed, the following things happen:
A new object is created, inheriting from Foo.prototype.
The constructor function Foo is called with the specified arguments, and with 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.
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.)
'new' will create a function object. When you just call a function, 'this' will be referred to the window. But if its a 'new' object, then the 'this' referred to the object itself.
I am giving some general information about the usage of "new" with "functions" in java script.
1. "new" can be used for functions as well. It will be considered as function constructor. When we do this way, as a general coding practice, we name the function with first character being upper case
When JS engine sees a "new" operator(yes "new" is an operator and has precedence"), it creates an empty object in memory and the engine will assign "this" reference to this newly created empty object.
At the end of the function constructor, JS engine will populate the empty object with the properties that we create inside constructor function and automatically return the object.
example:
//This is a function constructor which accepts two parameters
function Human(firstname, lastname) {
this.firstname = firstname; // "this" will point to humanIdentity
this.lastname = lastname;
// JS engine will automatically return the object with above properties
}
var humanIdentity = new Human('Mr.', 'JS');

Is it possible to recreate the "new" operator in JS? [duplicate]

This question already has answers here:
Simulate the 'new' operator in JavaScript
(4 answers)
Closed 6 years ago.
I recently read the MDN documentation on the new operator, and I was struck by the concise description of what it does:
When the code new Foo(...) is executed, the following things happen:
A new object is created, inheriting from Foo.prototype.
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.
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.)
It seems like none of those things are privileged operations, so is it possible to completely recreate the action of new with other language constructs?
Note that I don't count Reflect.construct since the very definition of it is that it "acts like the new operator as a function".
This function pretty much recreates Reflect.construct, and thus new (with the exception of construct's last argument, which has no equivalent when using the new operator:
function fauxNew (constructor, args) {
// allocate a new object and set the prototype
var newObject = Object.create(constructor.prototype)
// call the constructor with "this" bound to the new object
var retVal = constructor.apply(newObject, args || [])
// if the constructor returned an object, return it;
// otherwise return the new object
var constructorReturnedAnObject =
!!retVal && ["object", "function"].indexOf(typeof retVal) !== -1
return constructorReturnedAnObject? retVal : newObject
}
Here is the same code presented alongside some test cases.

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

Javascript Object : Literal Vs Constructor [duplicate]

This question already has answers here:
Literal notation VS. constructor to create objects in JavaScript [duplicate]
(2 answers)
Closed 9 years ago.
For creating Javascript object, we can use Literal or Constructor way;
In Constructor way, we say;
function myObj(){
this.myProp1 = "abc";
this.myProp2 = "xyz";
}
In literal way, we say;
var myObj = {
myProp1:"abc",
myProp2:"xyz",
}
My question is when declaring properties, why there is a difference like why do we use "this.myProp1" in case of Constructor way and not use "this" in Literal way ?
The key difference between the two is in how they are intended to be used. A constructor, as its name suggests, is designed to create and set up multiple instances of an object. An object literal on the other hand is one-off, like string and number literals, and used more often as configuration objects or global singletons (e.g. for namespacing).
There are a few subtleties about the first example to note:
When the code is executed, an anonymous function is created and assigned to myObj, but nothing else happens. methodOne and methodTwo don't exist until myObj is explicitly called.
Depending on how myObj is called, the methods methodOne and methodTwo will end up in different places:
myObj():
Since no context is supplied, the this defaults to window and the methods will become global.
var app1 = new myObj():
Due to the new keyword, a new object is created and becomes the default context. this refers to the new object, and the methods will get assigned to the new object, which subsequently gets assigned to app1. However, myObj.methodOne remains undefined.
myObj.call(yourApp):
This calls my myObj but sets the context to be another object, yourApp. The methods will get assigned to yourApp, overriding any properties of yourApp with the same names. This is a really flexible method that allows multiple inheritance or mixins in Javascript.
Constructors also allow another level of flexibility since functions provide closures, while object literals do not. If for example methodOne and methodTwo rely on a common variable password that is private to the object (cannot be accessed outside the constructor), this can be achieved very simply by doing:
var myObj = function(){
var variableOne = "ABCD1234";
this.methodOne = function(){
// Do something with variableOne
console.log(variableOne);
};
this.methodTwo = function(){
// Do something else with variableOne
};
};
myObj();
alert(variableOne); // undefined
alert(myObj.variableOne); // undefined
If you wanted to make variableOne exposed (public) you'd do:
var myObj = function(){
this.variableOne = "ABCD1234";
this.methodOne = function(){
// Do something with variableOne
console.log(this.variableOne);
};
this.methodTwo = function(){
// Do something else with variableOne
};
};
myObj();
alert(variableOne); // undefined
alert(myObj.variableOne); // ABCD1234
When defining something literally, the object is being built directly in the code. It doesn't exist yet until it is complete. At that point, this would have no meaning (not that there is any need for it either).
To understand this in the object creation function, first realize that this is special in JavaScript. Whenever you call a function, you can pass anything you want to be this. In general, things like event handlers will pass the event-causing DOM object to be passed as this. In your code, you do this as: MyFunction.call(whatever_needs_to_be_this[, param0, param1]);. When you use the new operator, such as var mything = new SomeThing();, JavaScript is essentially doing something like:
var mything = {};
SomeThing.call(mything);
this in this case is going to be mything in your function.

Does a function declaration create an object in 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

Categories

Resources