Accessing private member variables from prototype-defined functions

前端 未结 25 1381
孤城傲影
孤城傲影 2020-11-22 14:48

Is there any way to make “private” variables (those defined in the constructor), available to prototype-defined methods?

TestClass = function(){
    var priv         


        
25条回答
  •  礼貌的吻别
    2020-11-22 15:18

    Try it!

        function Potatoe(size) {
        var _image = new Image();
        _image.src = 'potatoe_'+size+'.png';
        function getImage() {
            if (getImage.caller == null || getImage.caller.owner != Potatoe.prototype)
                throw new Error('This is a private property.');
            return _image;
        }
        Object.defineProperty(this,'image',{
            configurable: false,
            enumerable: false,
            get : getImage          
        });
        Object.defineProperty(this,'size',{
            writable: false,
            configurable: false,
            enumerable: true,
            value : size            
        });
    }
    Potatoe.prototype.draw = function(ctx,x,y) {
        //ctx.drawImage(this.image,x,y);
        console.log(this.image);
    }
    Potatoe.prototype.draw.owner = Potatoe.prototype;
    
    var pot = new Potatoe(32);
    console.log('Potatoe size: '+pot.size);
    try {
        console.log('Potatoe image: '+pot.image);
    } catch(e) {
        console.log('Oops: '+e);
    }
    pot.draw();
    

提交回复
热议问题