Accessing an object's property from an event listener call in Javascript

后端 未结 6 1500
借酒劲吻你
借酒劲吻你 2020-12-05 05:00

Below I am creating an object in Javascript. Within the constructor I am setting up an event listener. The problem is that when the event gets fired, this.prop cannot be fou

6条回答
  •  既然无缘
    2020-12-05 05:34

    You have some typos on your function declaration.

    Your prop variable is also defined as a "public" or "visible" member (by using this.prop), doing so forces you to store the reference of this from the outer function (that is actually a reference to the object instance), as a "private" member of the function (using var) to get access the instance of the created object and read the "public" prop member.

    You have some alternatives to rewrite this code:

    function someObj (){
        var self = this;
        this.prop = 33;
        this.mouseMoving = function() { alert(self.prop);} // You access the current
                                                           // instance, stored in *self*
                                                           // since *this*, inside the 
                                                           // function, is in another 
                                                           // context.
        //...
    }
    
    var mySomeObj = new someObj(); // Object instantiation
    

    Or you could:

    function someObj (){
        var prop = 33;
        this.mouseMoving = function() { alert(prop);} 
    
        //...
    }
    var mySomeObj = new someObj(); // Object instantiation
    

    The variables declared with var, are accesible to the functions declared inside of the major constructor function, this feature is known as Closures.

提交回复
热议问题