Ankur
Ankur

Reputation: 51100

How do you add methods to a javascript object and use the object's variables

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?

Upvotes: 0

Views: 163

Answers (3)

Bergi
Bergi

Reputation: 664307

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.

Upvotes: 3

Ry-
Ry-

Reputation: 224877

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

Upvotes: 1

scunliffe
scunliffe

Reputation: 63580

To access any property on an Object just use:

this.file
this.id
this.{nameOfProperty}

Upvotes: 2

Related Questions