js: accessing scope of parent class

前端 未结 7 639
生来不讨喜
生来不讨喜 2021-01-31 13:45

I have a jquery class within a normal class in javascript. Is it possible to access variables in the scope of the parent class from a callback function in the jquery class?

7条回答
  •  谎友^
    谎友^ (楼主)
    2021-01-31 14:15

    By setting "this" to a variable you can access easily. Like:

    $("#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.'); }
        }
    })
    

提交回复
热议问题