js:访问父类的范围

时间:2011-02-24 14:55:13

标签: javascript jquery class scope parent

我在javascript中的普通类中有一个jquery类。是否可以从jquery类中的回调函数访问父类范围内的变量?

我的意思的一个简单示例如下所示

var simpleClass = function () {    
    this.status = "pending";
    this.target = jqueryObject;
    this.updateStatus = function() {
        this.target.fadeOut("fast",function () {
           this.status = "complete"; //this needs to update the parent class 
        });
    };
};

现在在上面的示例中,回调函数尝试访问jquery对象的范围。有没有办法访问父类中的状态变量?

7 个答案:

答案 0 :(得分:92)

将“this”设置为父函数中的变量,然后在内部函数中使用它。

var simpleClass = function () {         
    this.status = "pending";     
    this.target = jqueryObject;     

    var parent = this;

    this.updateStatus = function() {         
            this.jqueryObject.fadeOut("fast",function () {            
                parent.status = "complete"; //this needs to update the parent class          
            });     
        }; 
    }; 

答案 1 :(得分:31)

我会将这个问题的答案发布到这个旧问题上,因为之前还没有人发布过这个问题。

您可以在函数调用中使用bind方法来定义this所属的范围。

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind

每次创建方法时,

Normaly - this属于函数的当前范围。 scope2中的变量无法查看scope1中的变量。

e.g。

function(){
    // scope 1
    this.baz = 'foo';

    function(){
        // scope 2
        this.baz // not defined
    };
};

使用bind方法,您可以在函数内部this定义范围。因此,使用.bind(this),您告诉被调用的函数,他们自己的this范围被称为父函数的范围,如:

function(){
    // scope 1
    this.baz = 'foo';

    function(){
        // scope 1
        this.baz // foo
    }.bind(this);
};

所以在你的情况下,这是一个使用bind方法

的例子
var simpleClass = function () {    
    this.status = "pending";
    this.target = jqueryObject;
    this.updateStatus = function() {
        this.target.fadeOut("fast",function () {
           this.status = "complete"; //this needs to update the parent class 
        }.bind(this));
    }.bind(this);
};

答案 2 :(得分:4)

使用Arrow Function

  

箭头功能没有它自己的this。使用封闭词法范围的this值;箭头函数遵循常规变量查找规则。因此,在搜索当前范围中不存在的this时,他们最终会从其封闭范围中找到this

正常函数语法

function(param1, param2) {}

箭头功能语法

(param1, param2) => {}

<强>用法

const simpleClass = function () {    
    this.status = "pending";
    this.target = jqueryObject;
    this.updateStatus = function() { 
        this.target.fadeOut("fast", () => { // notice the syntax here
           this.status = "complete"; // no change required here
        });
    };
};

在ECMAScript 2015类中使用箭头功能

class simpleClass {

    constructor() {
        this.status = 'pending';
        this.target = jqueryObject;
    }

    updateStatus() {
        this.target.faceOut('fast', () => {
            this.status = "complete";
        });
    }
}

const s = new simpleClass();
s.updateStatus();

描述的代码仅适用于modern browsers

答案 3 :(得分:2)

对不起m8。您必须将引用嵌入到对象中,如下所示:

var simpleClass = function () {
    var _root = this;
    this.status = "pending";
    this.target = jqueryObject;
    this.updateStatus = function() {
        this.root = _root;
        _root.target.fadeOut("fast",function () {
           this.status = "complete"; //this needs to update the parent class 
        });
    };
};

注意var _root

答案 4 :(得分:2)

通过将&#34;此&#34; 设置为您可以轻松访问的变量。像:

$("#ImageFile").change(function (e) {
    var image, file;
    var Parent=this;
    if ((file = Parent.files[0])) {
        var sFileExtension = file.name.split('.')[file.name.split('.').length - 1];

        if (sFileExtension === "jpg" || sFileExtension === "jpeg" || sFileExtension === "bmp" || sFileExtension === "png" || sFileExtension === "gif") {
            var reader = new FileReader();

            reader.onload = function (e) {
               alert(Parent.files[0].name);
            };
            reader.readAsDataURL(Parent.files[0]);
        }
        else { alert('Wrong file selected. Only jpg, jpeg, bmp, png and gif files are allowed.'); }
    }
})

答案 5 :(得分:1)

试试这个:

   var sc = (function(scc){

    scc = {};

    scc.target = jQueryObject;


    scc.stt = "stt init";

    scc.updateStatus = function(){
        var elem = this;

        this.target.click(function(){
            elem.stt= "stt change";
            console.log(elem.stt);
        })

    }

    return scc;


}(sc || {}));

您还可以将目标对象定义为私有变量

答案 6 :(得分:0)

您可以使用闭包变量维护状态:

function simpleClass() {
   var _state = { status: "pending", target: jqueryObject; }

   this.updateStatus = function() {
      this.target.fadeOut("fast",function () {
         _state.status = "complete"; //this needs to update the parent class 
      });
   }
}

// Later...
var classInstance = new simpleClass();