שלח תשובה

זירת השאלות

1370
צפיות
9
תשובות

למה אני לא מצליח להציג את התוצאה כאשר אני מריץ את הפקודה alert(B.test());

,‏ 20 בספטמבר, 2012

היי,
למה אני לא מצליח להציג את התוצאה כאשר אני מריץ את הפקודה alert(B.test()); ?
י
ש לי קוד שעובד יפה http://jsfiddle.net/centerwow/nHetS/1/

function Shape(){}
Shape.prototype.name = 'shape';
Shape.prototype.toString = function() {return this.name;};

var F = function(){};
F.prototype = Shape.prototype;

function Triangle(side, height) {
this.side = side;
this.height = height;
}

Triangle.prototype = new F();
Triangle.prototype.constructor = Triangle;
Triangle.prototype.name = 'Triangle';

var my = new Triangle(5, 10);
alert(my.toString());

אני יוצר אוביקט בשם my שנוצר מ Triangle שיורש מ F
שיורש מ Shape
ב Shape יש מטודה בשם toString ואני יכול לגשת אליה מהאוביקט שנוצר בשם
my ולהציג את השם של מחלקה 'Triangle' ע"י הפוקדה alert(my.toString());

עד כאן הכל טוב ועובד.

עכשיו שכיפלתי את הקוד אבל אם שמות שונים ואני מנסה לגשת למטודה שיצרתי ב Shape
בשם test עם אותו רעיון בדיוק.
באמצעות הפקודה הבאה alert(B.test());
וזה לא עובד.
הקוד המלא בקישור: http://jsfiddle.net/centerwow/nHetS/

function Shape(){}
Shape.prototype.name = 'shape';
Shape.prototype.toString = function() {return this.name;};

var F = function(){};
F.prototype = Shape.prototype;
F.prototype.test = function(){return 'test';};


function Triangle(side, height) {
this.side = side;
this.height = height;
}

Triangle.prototype = new F();
Triangle.prototype.constructor = Triangle;
Triangle.prototype.name = 'Triangle';

var my = new Triangle(5, 10);
alert(my.toString());

var Secend_class = function(){};
Secend_class.prototype = Shape.prototype;
B.prototype = new Secend_class();
alert(B.test());​

9 תשובות

  1. centerwow הגיב:

    האם הקוד הבא לא מגדיר את B

    var Secend_class = function(){};
    Secend_class.prototype = Shape.prototype;
    B.prototype = new Secend_class();
    alert(B.test());?

  2. זאת לא הגדרה של B. אתה כתבת פה B.prototype כאילו שB קיים ואתה מרחיב אותו. prototype זה כדי להוסיף משתנים ופונק' לאובייקט שהגדרת כבר.

שלח תשובה