I am learning Object Oriented Java Script. I have below code for Factory Method.
function Foo() {
var value = 1;
return {
method: function() {
return value;
},
value:value
}
}
Foo.prototype = {
bar: function() {}
};
new Foo();
Foo();
method Foo can be called by two ways. new Foo(); or Foo(); Both do the same thing and output is same. what is actual difference in java script processing ?
In normal cases,
newshould be used when creating objects from a constructor function and eschewed when performing any other function call. When usingnewon a function 1) a new object is created; 2) the function is called with the value ofthisbound to that new object, and 3) the value returned from the function (by default) is the object created in step one.However, in your case you’re returning a completely new object from the “constructor” (different from the object in 1) above), which means there is no practical difference. The value of
thiswill still be different inside the function, but both of these will returnfalse:To illustrate the
thisdifference, add the following toFoo:When called with
newthis alertstrue; when called without it,false.Furthermore, there’s no point in assigning an object to
Foo.prototypebecause you’ll never create any instances ofFoothat would make use of it (because, again, you’re returning something completely different fromFoo).If you’re going to return a custom object from
Foothen you should prefer the version withoutnew; there’s no point in creating a new instance ofFooif you’re going to ignore it and return something completely different, anyway.