简体   繁体   English

Javascript将功能分配给现有变量

[英]Javascript assign function to existing variable

Example code: 示例代码:

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

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

    }
}

How can I assign thisFunc to someVar ? 如何将thisFunc分配给someVar If I do someVar = new thisFunc() , someVar.text will be gone. 如果我执行someVar = new thisFunc()someVar.text将消失。

Thank you. 谢谢。

I think you want something like bellow:- 我想你想要像下面这样的东西:

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

var thisFunc = function(){
  //do some
}
someVar.func = thisFunc;

It seems that an extend function would come in handy in your situation. 在您的情况下,似乎可以使用extend功能。 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): 这是一个小助手功能,它将一个对象的属性分配给另一个对象(如果您使用的是Underscore之类的第三方库,则可能已经有这样的功能了):

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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM