JavaScript - referencing 'this' in an inner function

后端 未结 4 1498
小鲜肉
小鲜肉 2021-01-23 15:04

Consider the following code:

MyClass.prototype.my_func = function () {
    this.x = 10;
    $.ajax({
        // ...
        success: function (data) {
                   


        
4条回答
  •  迷失自我
    2021-01-23 15:59

    the this syntax usually refers to the object, not a function. In your case, this refers to MyClass.

    If you're using the variable in the object, you probably forgot to define x in MyClass.

    If you're using the variable within the function ONLY I'd define my variables using the var syntax. Variables defined within a function are destroyed when a function ends.

    MyClass.prototype.my_func = function () {
        var x = 10;
    
        $.ajax({
            // ...
            success: function (data) {
                alert(x);
            }
        });
    }
    

提交回复
热议问题