简体   繁体   English

在javascript继承方案中,构造函数调用时未定义参数

[英]In javascript inheritance scheme, an argument became undefined on constructor call

I would like to build a basic inheritance OOP scheme to use. 我想建立一个基本的继承OOP方案来使用。 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上画出基本线条:

$(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 . 使用Chrome和Safari调试器时,从RNView构造函数调用RNLineView构造函数时,参数paper变为undefined

When I scope from the RNLineView constructor, the argument was fined. 当我从RNLineView构造函数作用域时,该参数被罚款。

Did I miss something ? 我错过了什么 ?

 RNView.apply(this,paper); 

is your problem. 是你的问题。 You want to use .call() instead. 您想改用.call() I wonder how this threw no error if paper was not an empty array. 我想知道如果paper不是一个空数组,这怎么不会出错。

See What is the difference between call and apply? 请参阅致电与申请之间有什么区别? for a detailed explanation. 详细说明。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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