1

Example code:

var someVar = {};
someVar.text = "some text";

var thisFunc = function(){
    this.subfunc = function(){

    }
}

How can I assign thisFunc to someVar? If I do someVar = new thisFunc(), someVar.text will be gone.

Thank you.

1
  • 2
    Assign someVar.text after new thisFunc? Commented Jun 29, 2014 at 13:41

2 Answers 2

2

I think you want something like bellow:-

var someVar = {};
someVar.text = "some text";

var thisFunc = function(){
  //do some
}
someVar.func = thisFunc;
Sign up to request clarification or add additional context in comments.

Comments

0

It seems that an extend function would come in handy in your situation. It's a little helper function, that assigns properties of one object to another one (if you are using a third party library like Underscore, you might already have such a function available):

function extend(obj1, obj2) {
    for (var key in obj2) {
        if (Object.prototype.hasOwnProperty.call(obj2, key)) {
            obj1[key] = obj2[key];
        }
    }
    return obj1;
}

Then you can do:

var someVar = {};
someVar.text = "some text";

var thisFunc = function(){
    this.subfunc = function(){

    }
}

someVar = extend(thisFunc, someVar);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.