在Javascript中为变量分配方法

时间:2015-09-14 23:26:14

标签: javascript node.js

在下面基于某些条件的示例中,我应该从我的类调用foo方法或者从alternative.js调用foo方法;我在myFunc变量中分配方法并调用该变量但是如果我想调用myClass的foo方法,它会因为MyClass.prototype.myclass中的name未定义而中断。这里有解决方法吗?如果您需要更多说明,请与我们联系:

    MyClass.prototype.test = function(name) {
        var myClass;
        var myFunc;
        shouldWork = true;
        if(shouldWork){
            p = require('alternative.js')
            myFunc = p['foo'];
        }else{
            myClass= this.myclass(name);
            myFunc = myClass['foo'];

        }

        myFunc('bar');// if "shouldWork" is true it works, but if it is false, it fails
        //In other words, myClass.foo('bar') works but calling
       //the variable which is set to myClass['foo']


    }
    MyClass.prototype.myclass = function(name) {
        // Here I do some operations on name and if it is undefined it breaks!
        // name gets undefined if you foo method of myClass if you have it in
        //a variable, becuse it is not assiging name which is from prototype
    }

1 个答案:

答案 0 :(得分:0)

您可以使用.bind()将对象绑定到方法调用。例如,如果您尝试将特定对象的方法保存到myFunc,那么您可以这样做:

myFunc = myClass.foo.bind(myClass);

然后,当你以后做:

myFunc(...);

它实际上会使用对象引用myClass作为方法正确调用它。

有关详细信息,请参阅MDN reference on .bind()