elfs: (Default)
[personal profile] elfs
I have a great mystery about Javascript: What does the new operator do, exactly? According to the documentation, "The new operator creates instances of ECMA standard objects and custom objects derived from Object." Since all other objects in the standard are derived from Object this would seem to me to be a useless addition, but that's not my point.

I have not yet found a use for the new operator in my normal programming responsibilities, and believe me I'm doing some heavy-duty Javascript these days. My traditional constructor looks like this:

MyClass = function(arg1, arg2) { 
    function privateFunction(argX) {...}; 
    function privateFunction(argX) {...}; 
    return { 
        a: 0, 
        b: '', 
        f: function(argX) { // Does something with this.a, this.b and arg1 } 
    }; 
}; 
myObj1 = MyClass(1, 4); 
myObj2 = MyClass(5, 9);


Calling the function MyClass returns an object (all the { ... } stuff after the return statement) and Javascript knows that unless you create a deeper internal scope, the this operator refers to that { ... } thing all the time, so a, b, f, and anything else described in there is available as a member of myObj1 from the outside, and this from the inside. Since every time MyClass is invoked, it creates a new scope and then pushes the closure out onto the heap before collapsing the stack, there's no need to call new.

So, when would someone need to use new?
This account has disabled anonymous posting.
If you don't have an account you can create one now.
HTML doesn't work in the subject.
More info about formatting

Profile

elfs: (Default)
Elf Sternberg

March 2026

S M T W T F S
1234567
8910111213 14
15161718192021
22232425262728
293031    

Most Popular Tags

Style Credit

Expand Cut Tags

No cut tags
Page generated Apr. 11th, 2026 09:26 am
Powered by Dreamwidth Studios