0

I have onkeypress event and I want to manipulate element this. I also have if statement in the event function. The problem is that the keyword this is different inside the if statement block. Is it normal to be like this. What explanation do you have?

example:

$(o).find('input[name=numeric]').keypress(
    function (e) {
        var a = this; // the real object element which activate the trigger
        if (e.keyCode == 13) {
            var b = this; //here "this" is different object 
        }
        else
            window.ncb.helper.validator.numeric(e);
    }
);
Mike Cluck
  • 31,869
  • 13
  • 80
  • 91
TheChampp
  • 1,337
  • 5
  • 24
  • 41
  • console.log(a === b) –  May 20 '16 at 17:04
  • 1
    _"here "this" is different object"_... __NO...__ – Rayon May 20 '16 at 17:04
  • I'm sure that isn't true. Inside of your `if` block, try doing `console.log(a === b)`. I guarantee you it'll be `true`. – Mike Cluck May 20 '16 at 17:05
  • @PraveenKumar Right. It's proving that they're the *exact* same object. – Mike Cluck May 20 '16 at 17:06
  • @procrastinator Check it out bud: [Object comparison in JavaScript](http://stackoverflow.com/questions/1068834/object-comparison-in-javascript) and [How to determine equality for two JavaScript objects?](http://stackoverflow.com/questions/201183/how-to-determine-equality-for-two-javascript-objects) – Praveen Kumar Purushothaman May 20 '16 at 17:09
  • @PraveenKumar, Both the variables are pointing to the same reference.. That is the reason of _"true"_ – Rayon May 20 '16 at 17:12
  • @PraveenKumar I'm not trying to perform property-based equality. I'm saying that `a` and `b` refer to the exact same *instance* of an object. The [`this` scope does not change when entering an `if` block.](https://jsfiddle.net/0yt9bxse/) Please stop cluttering the comments with your misunderstanding. – Mike Cluck May 20 '16 at 17:12
  • 1
    @MikeC, There is point in being _rude_.. Praveens comment(_"That's not how you compare objects"_) is not totally invalid.. Just ain't applicable in current context... – Rayon May 20 '16 at 17:15
  • @Rayon His comments are a bit rude, [not constructive and chatty.](http://meta.stackexchange.com/questions/244203/what-does-not-constructive-mean-and-how-does-it-differ-from-too-chatty?lq=1) That's enough reason to request that he stop cluttering up the comments section. – Mike Cluck May 20 '16 at 17:18
  • @procrastinator I am not sure if the reference - will be the same? Not sure then. – Praveen Kumar Purushothaman May 20 '16 at 18:06

1 Answers1

0

I found the problem. At the start of the if statement all is fine and visible. After that I replace html content which this lives inside of the old replaced content. Thank you anyway.

TheChampp
  • 1,337
  • 5
  • 24
  • 41