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

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

    When you call generate_0_4 dynamically (using an implicit to_string()) it is returned to generateForLevelSkillAndCount as an ad-hoc function. Because it's in Window scope rather than Object scope, it can't reference this, and the internal call fails because this doesn't exist in that context.

    Here's how to see what's happening:

    generate_0_4 : function(count) {
        throw(this);
        return this.generate_generic_dots(count, 3);
    },
    

    With generator.generateForLevelSkillAndCount(0, 4, 1); you get [object Window] or [object DOMWindow].

    With generator.generate_0_4(1); you get what you're expecting (and what works): [object Object] or #.

提交回复
热议问题