【问题标题】:Javascript/jQuery callback with classes带有类的 Javascript/jQuery 回调
【发布时间】:2012-08-18 17:01:00
【问题描述】:

我正在尝试在 javascript 上使用“类”(原型),但遇到了一个奇怪的“未定义”错误。

/**
 * Use the camera to take a picture and use it as custom image.
 */
function CameraMedia(imgTag, saveButton){
    this.__camera__ = navigator.camera;
    this.__imageTag__ = imgTag;
    this.__saveButton__ = saveButton;
    this.__selectedImage__ = null;
}

/**
 * Executes the camera of the device.
 * @param {Object} type selects between gallery or camera. Parameters could be "GALLERY" or "CAMERA" ignoring case.
 */
CameraMedia.prototype.run = function(type){
    var that = this;
    function onDeviceReady(){
          var options = {
              quality: 50,
              allowEdit : true
          };
          that.__camera__.getPicture(that.__successOperation__, that.__errorOperation__, options);
    }
    document.addEventListener("deviceready", onDeviceReady, true);
};

/**
 * Operation that might be performed in case of success in taking the image.
 */
CameraMedia.prototype.__successOperation__ = function(imageData){
    this.__selectedImage__ = imageData;
    $(this.__imageTag__).attr("src", imageData);
    $(this.__imageTag__).attr("image-changed", true);
    $(this.__saveButton__).show();
}

/**
 * Operation that might be performed in case of error in taking the image.
 */
CameraMedia.prototype.__errorOperation__ = function(message){
    alert(message);
}

问题是__successOperation__ 上的this 元素没有引用CameraMedia 对象。 谢谢。

【问题讨论】:

    标签: javascript class jquery-mobile scope this


    【解决方案1】:

    这是正常的。您正在将一个函数从一个对象(基本上是一个哈希图)传递给回调,而不是整个对象。

    为了解决这个问题,jQuery 有一个代理方法(下划线有一个绑定方法),它们是这样的:

    that.__camera__.getPicture($.proxy(that.__successOperation__, that), that.__errorOperation__, options);
    

    如果你想使用 vanilla javascript,你也可以实现这一点(示例 3):

    var a = {
        data: "1",
        func: function() {
            console.log(this.data);
        }
    };
    
    //This will log out undefined (Example #1)
    var myFunction = function(callback) {
        callback();
    };
    myFunction(a.func);
    
    //This will work (Example #2)
    var myFunction2 = function(callback) {
        callback.func();
    };
    myFunction2(a);
    
    //This will also work (Example #3)
    myFunction(function() {
        a.func()
    });​
    

    JSFiddle:http://jsfiddle.net/PBxFs/

    【讨论】:

    • 哎呀我不知道!非常感谢它就像一个魅力! ;)
    猜你喜欢
    • 2011-07-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-26
    • 1970-01-01
    • 1970-01-01
    • 2017-02-16
    • 2012-12-19
    相关资源
    最近更新 更多