In Javascript, why is the “this” operator inconsistent?

后端 未结 8 1694
挽巷
挽巷 2020-11-22 15:04

In JavaScript, the \"this\" operator can refer to different things under different scenarios.

Typically in a method within a JavaScript \"object\", it refers to the

8条回答
  •  悲哀的现实
    2020-11-22 16:03

    In JavaScript, this always refers to the object invoking the function that is being executed. So if the function is being used as an event handler, this will refer to the node that fired the event. But if you have an object and call a function on it like:

    myObject.myFunction();
    

    Then this inside myFunction will refer to myObject. Does it make sense?

    To get around it you need to use closures. You can change your code as follows:

    function TestObject() {
        TestObject.prototype.firstMethod = function(){
            this.callback();
            YAHOO.util.Connect.asyncRequest(method, uri, callBack);
        }            
    
        var that = this;
        TestObject.prototype.callBack = function(o){
            that.secondMethod();
        }
    
        TestObject.prototype.secondMethod = function() {
             alert('test');
        }
    }
    

提交回复
热议问题