When you invoke Obj
as a constructor by using the new
operator, always an object is returned. If the defined return value isn't of type Object
, it's just ignored. Within Obj
the object to be generated is referenced by this
, that is, every property assigned to this
is going to be a property of each generated object.
When you invoke Obj
as a normal function, it just returns the defined return value and this
is ignored.
name
and that
are just local variables with Obj
as scope. They're not assigned to this
and thus not part of the returned object. Since the return value name
is of type String
, it's simply ignored (if invoked as a constructor) and instead an object is returned, which contains all properties assigned to this
(so .name = "Alex"
):
var Obj = function () {
var name = "David" // local variable
this.name = "Alex" // name property of each newly generated object
return name;
}
var o = new Obj(); // invoke function as a constructor
var p = Obj(); // normal function invocation
console.log(o); // {name: "Alex"}
console.log(p); // "David"