0

I have this fiddle http://jsbin.com/EvIYomiF/4/ and just to noticed in case that its matter the javascript is in two files.

Well.. as you can see in the demo, the dom scope is being overwritten somehow and I want to understand why. I mean, the self=this hack is for sure a bad practice, but I don't understand why is being overwritten

I don't find words to describe the problem, I'm sorry for that, but the fiddle is the only way that I found to explain my problem easyly.

raulricardo21
  • 2,499
  • 4
  • 20
  • 27
  • Because the `on` jQuery method passes the element as context. `this` depends on **how** you call a function, it's dynamic. – elclanrs Nov 16 '13 at 01:36
  • You've got `cta = {}` and then `this.cta = $(cta)` - that will result in a more-or-less useless jQuery object. You initialize "cta" to be an ampty object, and then put a jQuery wrapper around it. What do you expect that to do? (It won't really do anything useful.) – Pointy Nov 16 '13 at 01:39
  • @Pointy you are right, I don't quite understand and that is why I'm asking. I'm trying to understand why this way is (so) wrong :P – raulricardo21 Nov 16 '13 at 01:43
  • What I do now now, is how to solved, I just curious about, because I don't understand why the override is happening. And also I do know that I'm using a weird way to do a simple thing. But for me the scope should be separeted – raulricardo21 Nov 16 '13 at 01:45
  • It's not weird behavior, it is normal JavaScript behavior. You can change the context of a function at runtime, `this` is not a reference to anything, it all depends on how a function gets called. Just look in Google for "JavaScript this keyword", you'll find plenty of information. `self = this` is common thing to do. – elclanrs Nov 16 '13 at 01:51

1 Answers1

4

All the conjecture about this is irrelevant and everyone has been leading you down the wrong trail.

The problem is that self has not been insulated by using var so it is therefore global. The second self overwrites the first.

Simply making it var self=this makes it all work. What you have done is common practice to avoid the change of context of this within the jQuery event handler

DEMO

charlietfl
  • 170,828
  • 13
  • 121
  • 150
  • Finally! Thank you @charlietfl, I did think for a moment that self could turn global inside of that function. Also thanks for the demo. If you, by chance have some link with information related that would be great. – raulricardo21 Nov 16 '13 at 12:30
  • 1
    Any time you don't use `var` it makes varible rise to top in scope creating unexpected behavior. Is best practice to always,always use it. Just search for javascript scope and javascript closure – charlietfl Nov 16 '13 at 12:36