JavaScript继承
我试图在javascript中实现继承。我想出了以下最小代码来支持它。
function Base(){ this.call = function(handler, args){ handler.call(this, args); }}Base.extend = function(child, parent){ parent.apply(child); child.base = new parent; child.base.child = child;}
专家,请告诉我这是否足够或我可能错过的任何其他重要问题。根据面临的类似问题,请提出其他更改建议。
这是完整的测试脚本:
function Base(){ this.call = function(handler, args){ handler.call(this, args); } this.superalert = function(){ alert('tst'); }}Base.extend = function(child, parent){ parent.apply(child); child.base = new parent; child.base.child = child;}function Child(){ Base.extend(this, Base); this.width = 20; this.height = 15; this.a = ['s','']; this.alert = function(){ alert(this.a.length); alert(this.height); }}function Child1(){ Base.extend(this, Child); this.depth = 'depth'; this.height = 'h'; this.alert = function(){ alert(this.height); // display current object height alert(this.a.length); // display parents array length this.call(this.base.alert); // explicit call to parent alert with current objects value this.call(this.base.superalert); // explicit call to grandparent, parent does not have method this.base.alert(); // call parent without overriding values }}var v = new Child1();v.alert();alert(v.height);alert(v.depth);
白衣非少年
相关分类