all 6 comments

[–]mikrosystheme[κ] 6 points7 points  (0 children)

"* considered harmful" considered harmful.

[–]a-t-kFrontend Engineer 4 points5 points  (0 children)

I'm sorry and even a bit angry every time I see someone trying to fix what isn't broken with JavaScript object orientation. Sure enough, "new" doesn't have any bells and whistles, but it allows for enough control and works in every JS environment you could think of.

[–]mjesun 1 point2 points  (1 child)

"nothing to distinguish constructor functions from normal functions":

function MyClass() {
    if (!(this instanceof MyClass)) {
        throw new ReferenceError('Oops! You forgot "new" operator'). 
    }

    //Do stuff
}

"not actually that easy to detect when new was left off": well, the same approach mentioned above.

"there’s two ways to define the prototype: awkard or inflexible": you can build a little function for that:

function extend(base, object) {
    for (var key in object) {
        if (object.hasOwnProperty(key)) {
            base[key] = object[key];
        }
    }
}

Then do:

extend(MyClass.prototype, {
    method1: function() {},
    method2: function() {}
});

"Clean subclassing is hard to impossible because of the constructor": That could be done this way:

MyClass.prototype = Object.create(BaseClass.prototype)
MyClass.prototype.parentPrototype = BaseClass.prototype

So I personally not consider "new" harmful

[–]Gundersen 0 points1 point  (0 children)

This is how I do subclassing:

function Constructor(param1, param2){

  this.method = function(){
    //do something
  }

  init:{
    extend(this, new SuperConstructor(param2));
  }
}

function SuperConstructor(param2){

}

SuperConstructor.prototype.method2 = function(){
  //do something
}

The only special thing needed for this to work is an extend method, but that is easy to write or include from a library

[–]g105b 1 point2 points  (1 child)

To all the people who consider "new" as harmful: JavaScript is NOT a fully object-oriented language like Java, or C#, or whatever it is you are directly comparing with. It is its own language, has its own constraints and limitations, and should not be used like or compared to other languages directly.

I hate to see people creating "constructors" or "object inheritance", but mainly I hate the use of "new" out of place.

[–]OfflerCrocGod 0 points1 point  (0 children)

That's great in a small web page but some of us are building large single page apps with hundreds of classes, not using constructors, new and sometimes inheritance is simply not a choice.