Oh, Mighty LJ Brain (Javascript Edition)
Sep. 14th, 2007 01:41 pmI 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:
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?
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?
no subject
Date: 2007-09-15 12:43 am (UTC)Someone programming Javascript who's actually bothered to look at the standard! :)
no subject
Date: 2007-09-15 03:55 am (UTC)