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

后端 未结 6 1873
爱一瞬间的悲伤
爱一瞬间的悲伤 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:03

    In JavaScript, the context object (this) is set to the "global object" (window, in browsers) unless the method is accessed as an object property. Therefore:

    var foo = { bar: function() { alert(this.baz); }, baz: 5 };
    var bar = foo.bar;
    var baz = 3;
    
    foo.bar();    // alerts 5, from foo
    foo["bar"](); // alerts 5, from foo
    bar();        // alerts 3, from the global object
    

    Note that all three function calls are to the exact same function!

    So, in your code, you're assigning the desired method to functionCall and calling it directly, which causes the function to use window as its context object. There are two ways around this: access the method as an object property or use .call() or .apply():

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

提交回复
热议问题