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

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

    This is a feature of Javascript: the value of this will depend on the object from which the function was called, not where it was defined. (Which makes sense when functions are first-class objects themselves.) this in most other contexts refers to the window object.

    There are two common workarounds, using a wrapper function:

    function bind(func, obj) {
        return function() {
            func.apply(obj, arguments);
        }
    }
    

    or using a closure:

    var self = this;
    function generate_blah() {
        // use self instead of this here
    }
    

    In your case, though, simply replacing

    var functionCall = this['generate_' + level + '_' + skill];
    return functionCall(count);
    

    with

    this['generate_' + level + '_' + skill](count);
    

    would do the trick.

提交回复
热议问题