简体   繁体   中英

access private object variable from public method

How can I access ctx in the function loadImage ? I have seen snippets that worked exactly like this but It just doesn't work when I try it. It always says 'this' or 'this.ctx' or 'ctx' is undefined.

var MyClass= function(canvasId){
  var canvas = document.getElementById(canvasId);
  var ctx = canvas.getContext("2d");
};
MyClass.prototype.loadImage = function(imageSrc){
    var image = new Image();
    image.src = imageSrc;
    //cannot access this or ctx
    image.onload = function(){
        this.ctx.drawImage(image,0,0);
    };
    //can't even access it here:
    ctx.drawImage(image,0,0);

};
//window.onload = function(){
 var myObject= new MyClass("myCanvas");
 myObject.loadImage('myImage.jpg');

How can I access ctx in the function loadImage?

You cannot. Unless you create the loadImage function inside the constructor's scope. See Javascript: Do I need to put this.var for every variable in an object? for details.

I have seen snippets that worked exactly like this

Then those snippets didn't work either.

The only way you can access ctx from proptotype methods is to set it as an instance property using this keyword.

var MyClass = function (canvasId) {
    this.canvas = document.getElementById(canvasId);
    this.ctx = this.canvas.getContext("2d");
};

MyClass.prototype.loadImage = function (imageSrc) {
    var image = new Image();
    image.src = imageSrc;

    var self = this;
    image.onload = function () {
        self.ctx.drawImage(image, 0, 0);
    };

    this.ctx.drawImage(image, 0, 0);
};

Note that inside image onload handler you have different context: this no longer points to MyClass instance, but rather to image object instance. You can overcome it for example by saving a reference to proper this in some variable like self .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM