您的位置:首页 > Web前端 > JavaScript

javascript 继承

2014-01-13 00:04 204 查看
function Shape(id) {
this.id = id;
}
Shape.prototype.name = "shape";
Shape.prototype.toString = function () {
var result = [];
if (this.constructor.parent) {
result[result.length] = this.constructor.parent.toString();
}
result[result.length] = this.name;
return result.join(', ');
};

function TwoDShape(id) {
TwoDShape.parent.constructor.call(this, id);
}
//TwoDShape.prototype = new Shape();
//TwoDShape.prototype = Shape.prototype;
var F = function () {
}
F.prototype = Shape.prototype;
TwoDShape.prototype = new F();
TwoDShape.prototype.constructor = TwoDShape;
TwoDShape.parent = Shape.prototype;
TwoDShape.prototype.name = "2D shape";

function Triangle(id, side, height) {
Triangle.parent.constructor.call(this, id);
this.side = side;
this.height = height;
}

//Triangle.prototype = new TwoDShape();
//Triangle.prototype = TwoDShape.prototype;
var F = function () {
}
F.prototype = TwoDShape.prototype;
Triangle.prototype = new F();
Triangle.prototype.constructor = Triangle;
Triangle.parent = TwoDShape.prototype;
Triangle.prototype.name = "triangle";
Triangle.prototype.getArea = function () {
return this.side * this.height / 2;
}

// YUI
function extend(Child, Parent) {
var F = function () {
};
F.prototype = Parent.prototype;
Child.prototype = new F();
Child.prototype.constructor = Child;
Child.parent = Parent.prototype;
}

function Person(name){
this.name = name;
}
Person.prototype.say = function(){
return "Hi, I' m " + this.name + ". ";
}

extend(Developer,Person);
function Developer(name, language){
this.language = language;
Developer.parent.constructor.call(this,name);
}
Developer.prototype.say = function(){
return Developer.parent.say.call(this) + "I love " + this.language + ".";
}

/*
var javaDeveloper = new Developer("A","Java");
var javascriptDeveloper = new Developer("B","Javascript");
alert(javaDeveloper.say());
alert(javascriptDeveloper.say());
*/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: