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

Javascript 继承方法2

2007-09-14 05:50 363 查看
.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }
方法2基本上是方法1的封装,提供了一个专门的方法用于子类的继承,同时克服了方法1的两个缺点:
// namespace
JsDev = {};

JsDev.extend = function(subClass, baseClass) {
function inheritance() {}
inheritance.prototype = baseClass.prototype;

subClass.prototype = new inheritance();          // 改变子类的原型,使其原型与父类原型串连起来
subClass.prototype.constructor = subClass;       // 改变子类的构造函数
subClass.baseConstructor = baseClass;            // 保存对基类构造函数的引用,以便在子类中调用
subClass.superClass = baseClass.prototype;       // 保存对父原型的引用
}

//Person class
function Person(first, last) {
this.first = first;
this.last = last;
}

Person.prototype.toString = function() {
return this.first + " " + this.last;
};

//Employee class
function Employee(first, last, id) {
Employee.baseConstructor.call(this, first, last);  // 调用父类中的构造函数
this.id = id;
}

// subclass Person
JsDev.extend(Employee, Person);

Employee.prototype.toString = function() {
return Employee.superClass.toString.call(this) + ": " + this.id;  // 调用父类中被覆盖的同名方法
};

//Manager
function Manager(first, last, id, department) {
Manager.baseConstructor.call(this, first, last, id);
this.department = department;
}

// subclass Employee
JsDev.extend(Manager, Employee);

Manager.prototype.toString = function() {
return Manager.superClass.toString.call(this) + ": " + this.department;
};

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: