【问题标题】:How do you add methods to a javascript object and use the object's variables如何向 javascript 对象添加方法并使用对象的变量
【发布时间】:2013-02-17 16:24:46
【问题描述】:

我希望能够使用对象的成员变量:

function Upload(file, filename, id){
    this.file=file
    this.filename=filename
    this.id=id;
};

Upload.prototype.displayImage = function(btn){
    $.canvasResize(file,
        {
            width: 160,
            height: 0,
            crop: false,
            quality: 100,
            callback: function (data)
        {
            $('#'+btn).css("background", "url("+data+")")
        }
    });
};

我像这样访问对象和方法:

var upload = new Upload(frontPic, frontPicName, id);
  upload.displayImage("btnFrontUploadShow");

但是我得到了错误:

ReferenceError: file is not defined
$.canvasResize(file,

为什么不能在displayImage方法中使用file变量,如何声明displayImage才能使用file变量?

【问题讨论】:

标签: javascript oop object methods


【解决方案1】:

您需要区分变量和属性。您的构造函数 (file, filename, id) 的三个参数是该函数的 [local] 变量,不能从外部访问。

然而,您通过分配值在您的实例(通过this keyword 引用)上创建了属性(具有相同的名称)。在原型方法中,您只能访问这些属性,因此您需要为它们使用点成员运算符 - 具有该名称的变量未在函数的范围内定义(如异常消息明确指出的那样)。请改用this.file

【讨论】:

    【解决方案2】:

    没有办法“声明”它以便可以在所有原型方法中使用它——您必须使用this.file 而不是file

    替代方法是不使用原型方法:

    function Upload(file, filename, id) {
        this.file = file;
        this.filename = filename;
        this.id = id;
    
        this.displayImage = function(btn) {
            $.canvasResize(file,
                {
                    width: 160,
                    height: 0,
                    crop: false,
                    quality: 100,
                    callback: function(data)
                    {
                        $('#' + btn).css("background", "url(" + data + ")")
                    }
                }
            });
        };
    }
    

    【讨论】:

      【解决方案3】:

      要访问对象上的任何属性,只需使用:

      this.file
      this.id
      this.{nameOfProperty}
      

      【讨论】:

        猜你喜欢
        • 2023-03-10
        • 1970-01-01
        • 2013-01-18
        • 1970-01-01
        • 2015-05-27
        • 2013-09-23
        • 1970-01-01
        • 1970-01-01
        • 2011-01-01
        相关资源
        最近更新 更多