On 12/23/10, Michael Haufe (TNO) <[email protected]> wrote:
>> On 23.12.2010 18:28, Joel Dart wrote:
>> new is a bad part primarily because of its dangerous potential for adding
>> global variables.
>> Specifically, using the previous example
>>
>> > function A(x) {
>> > this.x = x;
>> > }
>>
>> > A.prototype.foo = function () {
>> > return this.x;
>> > };
>>
>> > // and instance of the constructor "A"
>> > var a = new A(10);
>>
>> If instead you accidentally forgot new:
>>
>> var a = A(10);
>>
>> A would be a normal function call and, inside A, “this” would point to the
>> global object. You’d create a new global variable x which is obviously
>> unintended. Using the Object.create pattern you have a consistent
>> experience and don’t have to validate if you and your coworkers properly
>> used “new.”
>
> Or simply do this in your constructors and it becomes an irrelevant
> point:
>
> function Point(x, y){
> if(!(this instanceof Point)
.................................^
Missing ')'.
> return new Point(x, y);
> this.x = x;
> this.y = y;
> }
>
I rather have it one way or the other. e.g.
makePoint(x, y);
- OR -
new Point(x, y);
I just don't like seeing any extra if/else in the code. I also don't
want to handle the case where somebody might be relying on an anomaly
of calling the constructor as a function call.
> Plus when using the constructor pattern, Java style "super" calls can
> be emulated with apply()
>
When Point has a superclass or when Point *is* the superclass?
ISTM that such example won't work when Point is the superclass.
function Point(x, y){
if(!(this instanceof Point)) {
alert("Point recurse");
return new Point(x, y);
}
this.x = x;
this.y = y;
}
function P3D(x, y, z) {
// A point is returned here, and `this` object
// does not have `x` and `y`.
Point.call(this, x, y);
this.z = z;
}
new P3D(1, 2, 3);
That violates LSP anyway and probably a fair example to show such violation.
Generally I keep the constructors private and only use factories and
return an interface object. Doing that avoids having to deal with
constructor issues.
--
Garrett
--
To view archived discussions from the original JSMentors Mailman list:
http://www.mail-archive.com/[email protected]/
To search via a non-Google archive, visit here:
http://www.mail-archive.com/[email protected]/
To unsubscribe from this group, send email to
[email protected]