Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is `this` sometimes undefined inside an object literal?

Tags:

javascript

Browser Error

  • TypeError: this is undefined

Related Code

// start of module

$A.module({
    Name: 'MUserNew',

...

    enter: (function (event) {
        var pipe = {};
        if (event.keyCode === 13) {
            pipe = $A.definePipe(this.Name); // **fail here**
            $A.machine(pipe);
        }
    }).bind(this),

...

        // inside module as well
        this.E.un_go.addEventListener("keypress", 
                                       this.enterB, 
                                       false);

1 Answers

You're doing the right thing by using .bind(), but unfortunately this does not have the behavior you expect. It does not take on the value of an "in progress" object inside an object literal. You have to make the object, set the handler, and then pass it to your "module" method.

You can still do it in one expression, like this:

$A.module(function() {
  var obj = {
    // ... 
    enterB: function(event) { ... },
    // ...
  };
  obj.enterB = obj.enterB.bind(obj);
  return obj;
}());
like image 92
Pointy Avatar answered Dec 16 '25 08:12

Pointy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!