0

I want to be able to use an object's member variables:

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+")")
        }
    });
};

I access the object and method like this:

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

However I am getting the error:

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

Why can't I use the file variable in the displayImage method, and how can I declare displayImage so that the file variable is available for use?

Ankur
  • 50,282
  • 110
  • 242
  • 312
  • 5
    You want to use `this.file` – Paul S. Mar 03 '13 at 15:08
  • 1
    More generally, all instance variables need to be accessed as `this.something`. – Xymostech Mar 03 '13 at 15:09
  • possible duplicate of [Javascript: Do I need to put this.var for every variable in an object?](http://stackoverflow.com/questions/13418669/javascript-do-i-need-to-put-this-var-for-every-variable-in-an-object) – Bergi Mar 03 '13 at 15:14

3 Answers3

3

You will need to distinguish between variables and properties. The three parameters of your constructor function (file, filename, id) are [local] variables to that function, and cannot be accessed from outside.

Yet, you created properties (with the same names) on your instance (referenced via the this keyword) by assigning them the values. In the prototype method, you can only access these properties, and so you will need to use the dot member operator for them - variables with that name are not defined in the function's scope (as the exception message clearly states). Use this.file instead.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
2

To access any property on an Object just use:

this.file
this.id
this.{nameOfProperty}
scunliffe
  • 62,582
  • 25
  • 126
  • 161
1

There’s no way to “declare” it so that it can be used in all prototype methods — you have to use this.file instead of file.

The alternative would be not to use a prototype method:

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 + ")")
                }
            }
        });
    };
}
Ry-
  • 218,210
  • 55
  • 464
  • 476