Question

I am not understanding JavaScript scoping and inheritance correctly. I clearly defined a function to take 1 argument (and I understand that this is optional due to how JavaScript handles arguments) but it looks like I need an extra argument to make the scoping work. Why is this?

ShapeRenderable.prototype = new Renderable();
function ShapeRenderable()
{
    this._line_join = 'round';
    this._line_cap = 'round';
    .
    .
} 

ShapeRenderable.prototype.setFillColor = function (fill_style)
{
    if (fill_style)
    {
        this._fill_style = fill_style;
        this.initialAlpha = fill_style._alpha;
    }
    else
    {
        this._fill_style = new RGBA(0,0,0,1.0);
    }
};



SelectionCube.prototype = new ShapeRenderable();

function SelectionCube()
{ 
    var self = this; // So we can access public methods and members from within
    // private ones.    

    self._visible = true;         
    self._scale = 1;
    self._stroke_style   = new RGBA(0,0,0,.1); // Lines solid black
    self._line_width = 7.0; // 1

    var platonicRenderable = new PlatonicRenderable(this);
    platonicRenderable.createCube(); 

    // surfaces mostly transparent white
    ShapeRenderable.prototype.setFillColor.call(this, new RGBA(255,255,255,1));
    // Why do I have to pass "this" to get the correct scope during 
    // execution of the above? If "this" isn't passed, it looks like JavaScript 
    // is scoping this for the parent, instead of for the child.
    // 
    // This is the correct behavior. My cube is now white.


}

If I just call:

ShapeRenderable.prototype.setFillColor.call(new RGBA(255,255,255,1));

Then my renderable is black (which is incorrect) and it looks like this._fill_style is never set correctly for my SelectionCube. Why is this? Is there some secret JavaScript optional (first) parameter which tells the function what scope to use during execution? I was having the above issue, and I read about passing this so that the class reference will still point to the child but I never understood why.

Here's what it looks like for the two cases: Broken Broken - Not Updating "this" correctly

Works Works - Updating "this" correctly

Was it helpful?

Solution

You're using .call incorrectly. The correct syntax for call is

fun.call(thisArg[, arg1[, arg2[, ...]]])

See the docs.

The first parameter is the "scope" or the this object within the function. Subsequent arguments are passed to your function's parameters.

However in this situation it's best to use @elclanrs suggestion in your comments.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top