Javascript面向对象 继承
//父类
function Class() {
this.name = "name";
this.method = function () {
alert("method");
}
}
//子类
function Class1() {
this.name1 = "name1";
this.method1 = function () {
alert("method1");
}
}
//子类继承父类
Class1.prototype = new Class();
var obj = new Class1();
alert(obj.name);
alert(obj.name1);
obj.method();
obj.method1();
/****** 子类继承父类的语法,子类.prototype=new 父类(); *****/
子类重写父类
//子类
function Class2() {
this.name2 = "name2";
this.method2 = function () {
alert("method2");
}
}
Class2.prototype = new Class(); //继承
Class2.prototype.name = "updateName"; //重写父类的属性
Class2.prototype.method = function () {//重写父类的方法
alert("UpdateMethod");
}
var obj2 = new Class2();
alert(obj2.name); //显示updateName
obj2.method(); //显示UpdateMethod
alert(obj2.name2);
obj2.method2();
//父类
function Class() {
this.name = "name";
this.method = function () {
alert("method");
}
}
//子类
function Class1() {
this.name1 = "name1";
this.method1 = function () {
alert("method1");
}
}
//子类继承父类
Class1.prototype = new Class();
var obj = new Class1();
alert(obj.name);
alert(obj.name1);
obj.method();
obj.method1();
/****** 子类继承父类的语法,子类.prototype=new 父类(); *****/
子类重写父类
//子类
function Class2() {
this.name2 = "name2";
this.method2 = function () {
alert("method2");
}
}
Class2.prototype = new Class(); //继承
Class2.prototype.name = "updateName"; //重写父类的属性
Class2.prototype.method = function () {//重写父类的方法
alert("UpdateMethod");
}
var obj2 = new Class2();
alert(obj2.name); //显示updateName
obj2.method(); //显示UpdateMethod
alert(obj2.name2);
obj2.method2();