Suppose I have the following function:
var A = function() {
var label = "hello";
return {
getLabel: function() { return label; }
}
};
Is there any difference between:
var a = A();
and
var a = new A();
?
NB: I'm not asking here what is the 'new' keyword in JavaScript, but how it behaves in this particular example.
New keyword in JavaScript is used to create an instance of an object that has a constructor function. On calling the constructor function with 'new' operator, the following actions are taken: A new empty object is created.
If I tried to access a property name in an object that does not exist, then I would get undefined. For example, if I tried developer. age then the return value would be undefined because the developer object does not have that property name. We can check if a property exists in the object by checking if property !==
The prototype property of a Javascript object is shared among all the instances/copies of the object and can be used to store shared data/state.
In your particular instance, No, there is no difference.
Eitherw way, your function will return a self defined Object. By invoking a function with the new
keyword, ECMAscript will automatically create a new object for you (alongside doing some magic with prototype
and constructor
properties), which you might access / write to via this
within the function (-constructor)
.
Again, your return { }
call in that function, will always return exactly that object reference.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With