Question

I would like to build a basic inheritance OOP scheme to use. I have an unexpected behavior and I do not understand why.

I use a simple helper function for prototype inheritance :

function inherits(p) {
    if (p == null) throw TypeError(); 
    if (Object.create)
        return Object.create(p);
    var t = typeof p;
    if( t !== "object" && t !== "function") throw TypeError();
    function f() {};
    f.prototype = p;
    return new f();
}

I have basic geometric objects :

function RNPoint(x, y){
    this.x = x;
    this.y = y;
}

function RNRect(x, y, width, height){
    this.topLeft = new Point(x,y);
    this.width = width;
    this.height = height;
}

I defined a class that contains informations about drawing color, stroke width, ... :

function RNView(paper){
    this.Rpaper = paper;

    this.strokeColor = "#000";
    this.fillColor = "#000";
    this.strokeWidth = 5;
}

RNView.prototype = {
    draw: function(robject){

        robject.attr({
            fill: this.fillColor,
            stroke: this.strokeColor,
            "stroke-width": this.strokeWidth
        });
    }
};

I subclass this object to draw a line :

function RNLineView(paper, startPoint, endPoint){

    RNView.apply(this,paper);

    this.startPoint = startPoint;
    this.endPoint = endPoint;

}

RNLineView.prototype = inherits(RNView.prototype);
RNLineView.prototype.constructor = RNLineView;

RNLineView.prototype.draw  = function()
{

    var d = "M " + this.startPoint.x + "," + this.startPoint.y + ' L' + this.endPoint.x + "," + this.endPoint.y;
    var path = this.Rpaper.path(d);

    RNView.prototype.draw(path);    
}

I wanted to test it and draw basic line at document.ready :

$(document).ready(function (){

   var paper = Raphael('canvas', 640, 480);

   var startPoint = new RNPoint(10,20),
        endPoint = new RNPoint(40, 60);

    var line = new RNLineView(paper, startPoint,endPoint);
});

With Chrome and Safari debugger, when the RNView constructor is called from the RNLineView constructor, the argument paper becomes undefined.

When I scope from the RNLineView constructor, the argument was fined.

Did I miss something ?

Était-ce utile?

La solution

RNView.apply(this,paper);

is your problem. You want to use .call() instead. I wonder how this threw no error if paper was not an empty array.

See What is the difference between call and apply? for a detailed explanation.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top