Javascript 'this' value changing, but can't figure out why

后端 未结 6 1869
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-14 08:52

I\'m a total Javascript newb, and I\'m trying to wrap my head around OLN. What I\'m encountering is that, when calling an object method from another method on the same objec

6条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-14 09:01

    First of all, I would encourage you to avoid eval where you don't need it, for example, in your fist function:

    //...
    generateForLevelSkillAndCount : function(level, skill, count) {
        var functionCall = this['generate_' + level + '_' + skill];
        return functionCall(count);
    },
    //...
    

    You can use the bracket notation property accessor instead eval, it's unnecessary in this case.

    Now, I guess you are trying your code on the Chrome's Console, and eval is failing because the console has a bug, when eval is invoked from a FunctionExpression (such as generateForLevelSkillAndCount), the evaluated code uses the Global context for its Variable Environment and Lexical Environment.

    See this answer for more information on this bug.

    Edit: After re-reading your code, the problem happens because you lose the base object reference when you assign the function to your functionCall variable, you can either:

    Invoke the function directly, without using that variable:

    //...
    generateForLevelSkillAndCount : function(level, skill, count) {
        this['generate_' + level + '_' + skill](count);
    },
    //...
    

    Or still use your variable, but persist the this value:

    //...
    generateForLevelSkillAndCount : function(level, skill, count) {
        var functionCall = this['generate_' + level + '_' + skill];
        return functionCall.call(this, count);
    },
    //...
    

    More info on this...

提交回复
热议问题