Why is "it" sometimes undefined inside an object literal?

Browser error

  • TypeError: it's 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);

      

+3


source to share


2 answers


You are doing the right thing by using .bind()

, but unfortunately this

does not have the expected behavior. It does not accept the value of an "in progress" object within an object literal. You have to make an object, set up a handler, and then pass it to your "module" method.

You can still do it in a single expression, for example:



$A.module(function() {
  var obj = {
    // ... 
    enterB: function(event) { ... },
    // ...
  };
  obj.enterB = obj.enterB.bind(obj);
  return obj;
}());

      

+4


source


You need to use bind(this)

inside a function definition to be defined this

(not undefined). The function must be called.



/*MUserNew
**
**
**            
*/
$A.module({
    Name: 'MUserNew',
    // ....
    init: function () {
        this.enter = this.enter.bind(this);

      

+1


source







All Articles