您好,欢迎访问一九零五行业门户网

js模拟类继承小例子_javascript技巧

复制代码 代码如下:
//使用原型继承,中间使用临时对象作为child的原型属性,临时对象的原型属性再指向父类的原型,
//防止所有子类和父类原型属性都指向通一个对象.
//这样当修改子类的原型属性,就不会影响其他子类和父类
function extend(child, parent) {
var f = function(){};
f.prototype = parent.prototype;
child.prototype = new f();
child.prototype.constructor = child;
child.base = parent.prototype;
}
function parent(name)
{
this.aa = 123;
this.getname = function() {return name;}; //使用闭包模拟私有成员
this.setname = function(value){name=value;};
}
parent.prototype.print = function(){alert(print!);};
parent.prototype.hello = function()
{
alert(this.getname() + parent)
};
function child(name,age)
{
parent.apply(this, arguments);//调用父类构造函数来继承父类定义的属性
this.age = age;
}
extend(child,parent); //继承parent
child.prototype.hello = function() //重写父类hello方法
{
alert(this.getname() + child);
parent.prototype.hello.apply(this,arguments); //调用父类同名方法
};
//子类方法
child.prototype.dosomething = function(){ alert(this.age + child dosomething); };
var p1 = new child(xhan,22);
var p2 = new child(xxx,33);
p1.hello();
p2.hello();
p1.dosomething(); //子类方法
p1.print(); //父类方法
alert(p1 instanceof child); //true
alert(p1 instanceof parent);//true
其它类似信息

推荐信息