Let us say I have the following object constructor:
function Foo(bar) {
this.bar = bar;
}
If I run the function in the global scope without the new
keyword then bar
will be set in whatever scope Foo()
is called in:
var foo = Foo(42);
console.log(bar); // 42
console.log(foo.bar); // ERROR
So my idea is to do something like this:
function Foo(bar) {
if(!(this instanceof Foo)) {
// return a Foo object
return new Foo(bar);
}
this.bar = bar;
}
That way if I do new Foo(42)
or Foo(42)
, it would always return a Foo
object.
Is this ever a good idea? If so, when? When (and why) would it be wise to avoid this technique?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…