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?
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();
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With