javascript tutorial - [Solved-5 Solutions] Javascript new keyord - javascript - java script - javascript array


Is javascript “new” keyword considered harmful ?

Solution 1:

Crockford has done a lot to popularize good JavaScript techniques. His opinionated stance on key elements of the language have sparked many useful discussions. That said, there are far too many people that take each proclamation of "bad" or "harmful" as gospel, refusing to look beyond one man's opinion. It can be a bit frustrating at times.

Use of the functionality provided by the new keyword has several advantages over building each object from scratch:

  • Prototype inheritance. While often looked at with a mix of suspicion and derision by those accustomed to class-based OO languages, JavaScript's native inheritance technique is a simple and surprisingly effective means of code re-use. And the new keyword is the canonical (and only available cross-platform) means of using it.
  • Performance. This is a side-effect of #1: if we want to add 10 methods to every object we create, we could just write a creation function that manually assigns each method to each new object... Or, we could assign them to the creation function's prototype and use new to stamp out new objects. Not only is this faster (no code needed for each and every method on the prototype), it avoids ballooning each object with separate properties for each method. On slower machines (or especially, slower JS interpreters) when many objects are being created this can mean a significant savings in time and memory.

And yes, new has one crucial disadvantage, ably described by other answers: if we forget to use it, our code will break without warning. Fortunately, that disadvantage is easily mitigated - simply add a bit of code to the function itself:

function foo()
   // if user accidentally omits the new keyword, this will 
   // silently correct the problem...
   if ( !(this instanceof foo) )
      return new foo();

   // constructor logic follows...
click below button to copy the code. By JavaScript tutorial team

Now we can have the advantages of new without having to worry about problems caused by accidentally misuse. We could even add an assertion to the check if the thought of broken code silently working bothers you. Or, as some commented, use the check to introduce a runtime exception:

if ( !(this instanceof arguments.callee) ) 
   throw new Error("Constructor called as a function");
click below button to copy the code. By JavaScript tutorial team

(Note that this snippet is able to avoid hard-coding the constructor function name, as unlike the previous example it has no need to actually instantiate the object - therefore, it can be copied into each target function without modification.)

John Resig goes into detail on this technique in his Simple "Class" Instantiation post, as well as including a means of building this behavior into our "classes" by default. Definitely worth a read... as is his upcoming book, Secrets of the JavaScript Ninja, which finds hidden gold in this and many other "harmful" features of the JavaScript language (the chapter on with is especially enlightening for those of us who initially dismissed this much-maligned feature as a gimmick).

Solution 2:

Javascript being dynamic language there a zillion ways to mess up where another language would stop you. Avoiding a fundamental language feature such as new on the basis that we might mess up is a bit like removing our shiny new shoes before walking through a minefield just in case we might get our shoes muddy. WE use a convention where function names begin with a lower case letter and 'functions' that are actually class definitions begin with a upper case letter. The result is a really quite compelling visual clue that the 'syntax' is wrong:-

var o = MyClass();  // this is clearly wrong.
click below button to copy the code. By JavaScript tutorial team

On top of this good naming habits help. After all functions do things and therefore there should be a verb in its name whereas classes represent objects and are nouns and adjectives with no verb.

var o = chair() // Executing chair is daft.
var o = createChair() // makes sense.
click below button to copy the code. By JavaScript tutorial team

Its interesting how SO's syntax colouring has interpretted the code above.

Solution 3:

We are newbie to Javascript so maybe we just not too experienced in providing a good view point to this. Yet we want to share my view on this "new" thing.

We have come from the C# world where using the keyword "new" is so natural that it is the factory design pattern that looks weird to me.

When we first code in Javascript, we don't realize that there is the "new" keyword and code like the one in YUWE pattern and it doesn't take me long to run into disaster. We lose track of what a particular line is supposed to be doing when looking back the code I've written. More chaotic is that my mind can't really transit between object instances boundaries when we am "dry-running" the code.

Then, we found the "new" keyword which to me, it "separate" things. With the new keyword, it creates things. Without the new keyword, We know we won't confuse it with creating things unless the function we invoking gives me strong clues of that.

For instance, with var bar=foo(); We have no clues as what bar could possibly be.... Is it a return value or is it a newly created object? But with var bar = new foo(); We know for sure bar is an object.

Solution 4:

Another case for new is what we call Pooh Coding. Winnie the Pooh follows his tummy. We say go withthe language we are using, not against it. Chances are that the maintainers of the language will optimize the language for the idioms they try to encourage. If they put a new keyword into the language they probably think it makes sense to be clear when creating a new instance.

Code written following the language's intentions will increase in efficiency with each release. And code avoiding the key constructs of the language will suffer with time.

EDIT: And this goes well beyond performance. We can't count the times I've heard (or said) "why the hell did they do that?" when finding strange looking code. It often turns out that at the time when the code was written there was some "good" reason for it. Following the Tao of the language is our best insurance for not having our code ridiculed some years from now.

Solution 5:

The rationale behind not using the new keyword, is simple: By not using it at all, we avoid the pitfall that comes with accidentally omitting it. The construction pattern that YUWE uses, is an example of how we can avoid the new keyword altogether"

var foo = function () {
    var pub= { };
    return pub;
var bar = foo();
click below button to copy the code. By JavaScript tutorial team

Alternatively we could so this:

function foo() { }
var bar = new foo();
click below button to copy the code. By JavaScript tutorial team

But by doing so we run risk of someone forgetting to use the new keyword, and the this operator being all fubar. AFAIK there is no advantage to doing this (other than we are used to it). At The End Of The Day: It's about being defensive. Can we use the new statement? Yes. Does it make our code more dangerous? Yes. If we have ever written C++, it's akin to setting pointers to NULL after we delete them.

Related Searches to javascript tutorial - Javascript new keyord