Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Javascript's new operator do anything but make life difficult?

Tags:

javascript

I come from the traditional web developer background where I can by no means claim to really know anything about Javascript, however I am trying.

I currently have what I would describe as a fairly novice understanding of JQuery, a slightly better understanding of closures, and I've read through, and feel like I am fairly clear on Douglas Crockford's "Javascript: The Good Parts".

I've been building up some fairly javascript intensive pages lately and I'm actually pretty satisfied with the results. One thing that stands to notice is that I managed to do the whole thing with almost no global functions and without using the new operator even once.

As a matter of fact, from my reading of the above-mentioned book, the operator does nothing that you could not do another simpler way and forces you to hack the 'this' variable.

So is there something I'm missing? Does the new operator actually serve a purpose or is it just a trick to make OO programmers comfortable in what is at heart a functional language? Would I be better off striking it entirely from my JS vocabulary?

like image 837
George Mauer Avatar asked Nov 16 '09 19:11

George Mauer


2 Answers

First of all, kudos on reading Javascript: The Good Parts it's a great book on the language.

To answer your question, the new operator is required if you want to make use of prototypal inheritance. There is no other way to have an object "inherit" from another. That being said, you can copy properties from one object to another that would remove the need for the operator in some cases.

For example, a classical approach would use the following:

function MyClass() {};
MyClass.prototype.sayHello = function() {
   alert('hello');
};


var o = new MyClass();
o.sayHello();

You can achieve relatively the same thing as follows:

function MyClass() {
   return { 
      sayHello: function() {
         alert('hello');
      }
   };
}

var o = MyClass();
o.sayHello();
like image 71
Bryan Kyle Avatar answered Oct 15 '22 21:10

Bryan Kyle


You brought up Crockford's "JavaScript: The Good Parts."

New is a bad part. Page 114. I don't use it. (Well, almost never.)

Crockford does use it (in his beget() method).

Definitely don't use it when you can use something else. Create objects and arrays with object and array literals.

like image 39
Nosredna Avatar answered Oct 15 '22 21:10

Nosredna