user6593942
user6593942

Reputation:

access/modify an object inside of a function | javascript

lets say I have a function - object constructor:

var constructor = function(name, surname, town){
    return {
        Name: name,
        Surname: surname,
        Town: town
    }
};

Now I can create a new obj like this:

var peter = constructor("Peter", "Jameson", "London");

and I can add new properties to my new object peter using dot notation like this:

peter.phoneNumber = 856687;

My question is: Is it possible to add more properties to my constructor using dot/bracket notation when the object in the constructor/function has no var?

Upvotes: 0

Views: 424

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074038

It sounds like you're trying to modify the behavior of constructor at runtime. You've said:

I would like to modify the code of constructor using dot notation (if its possible in this case), e.g. I would like to add more properties to my constructor. If the code was like this:

var constructor = function(name, surname, town){
    var person = { Name: name, Surname: species, Town: town };
    return person;
};

...then I guess I could modify my constructor like this: {constructor.person.phoneNumber = 554457; but in my original code constructor has no var inside so I cant taget obj

As @deceze pointed out, no, you couldn't do that even if constructor had a variable in it; that variable is entirely private to the function, it's not exposed as a property of constructor.

The only way1 to modify constructor's behavior at runtime is to wrap it in a new function, like this:

(function() {
    var original = constructor;
    constructor = function() {
        var obj = original.apply(this, arguments);
        obj.phoneNumber = 554457;
        return obj;
    };
})();

That calls the original version with all of the arguments it receives (and the same this), then adds the additional property, and returns it.


1 Okay, technically, you could decompile it with toString (on browsers that support it; support is now required as of ES5, so it's pretty good), use text manipulation to change its contents, then use new Function to turn it back into a function and assign the result to constructor, but A) It's a really bad idea, and B) The function would lose its context, and so if it relied on closing over any variables that aren't globals, it would stop working (hence [A]).

Upvotes: 1

Related Questions