在应用中,我们常常设计继承关系,当然静态属性也是很简单的,但是如果把这两者结合到一起,还是需要一些技巧的。
场景描述:
父类:定义静态属性类型,仅仅起到描述的作用,具体的实例化交给每一个子类去做。
定义抽象方法,并且在方法中会调用之前定义的静态属性。
子类:继承父类。子类对静态属性进行赋值。
子类的对象,调用父类的接口。
实现继承代码如下(不是重点):
function inherit(sub, sup) {
function F() {}
F.prototype = sup.prototype;
var parent = new F();
for(var arr in sub.prototype){
if(sub.prototype.hasOwnProperty(arr)){
parent[arr] = sub.prototype[arr];
}
}
sub.prototype = parent;
sub.prototype.constructor = sub;
sub._parent = parent;
return sub;
}父类代码如下:
var parent = function(){
}
parent.prototype={
gan:null, // 静态属性
shoot: function(){
this.gan.do(); // 调用静态属性。关键:不要用parent.prototype.gan
}
}子类代码如下:
var child = function(){
parent.apply(this, arguments);
if(!child.prototype.gan){
// 在子类中对静态属性进行初始化
child.prototype.gan = {do: function(){console.log(‘hello ..‘);}}
}
}
inherit(child, parent);子类实例化:
var cc = new child(); cc.shoot();// hello ..
本文出自 “技术人生” 博客,请务必保留此出处http://wangyuelucky.blog.51cto.com/1011508/1685013
原文:http://wangyuelucky.blog.51cto.com/1011508/1685013