Function的扩展(1):继承

做为技术类的开篇文章,非常纠结了一番到底写什么的。想了想,就写面向对象吧。。始终对于咱们程序员来讲,面向对象是写一篇好文章。对不起习惯了。应该说是写一篇好代码的开始。程序员

而面向对象的三大特征中最重要的就是继承了。ide

继承如今有不少种写法,google一下处处都是。我就再也不在这里重复了。直接上个人代码吧。测试

核心功能代码以下:this

Function.prototype.Implement = function (parentType) {
    //判断父类是否存在以及是否为可继承类型
    if (parentType != undefined && typeof (parentType) == "function") {
        var temp = this.prototype;
        this.prototype = new parentType();
        for (var i in temp) {
            this.prototype[i] = temp[i];
        }
        this.prototype.base = parentType.prototype;
    }
}

核心功能有了。让咱们来测试一下在js中传统继承所具备的特征吧。google

先声明父类
prototype

var parent= function () {
    //constructor
}
parent.prototype = (function () {
    //private
    return {
        //public
        SomeVar:"I'm the first generation"
        DoSomeStaff:function(){
           console.write(this.SomeVar);
        }
    };
})();

这里对你们进行一下推荐。这种类的声明方法。
对象

能够经过个人注释看到。有构造方法。有私有方法。有公有方法。继承

而后咱们声明一下继承类
it


var child= function () {
    //constructor
}
child.prototype = (function () {
    //private
    return {
        SomeVar:"I'm the second generation"
        DoSomeStaff:function(){
           this.base.DoSomeStaff.call(this);//调用父类的方法
        }
    };
})();
//这里表示child继承了parent
//是否是比传统的写法要更符合高级语言的语序?
child.Implement(parent)


而后咱们进行测试io


var p1=new parent();
p1.DoSomeStaff()//output:I'm the first generation
var c1=new child();
c1.DoSomeStaff()//output:I'm the second generation
c1 instanceof parent//true
c1 instanceof child//true


能够看见,我这个继承写法的好处在于在继承和调用父类的时候更接近高级语言的语序和语法。使得代码在阅读方面有所提升。


固然这个写法仍是有必定的局限性。

例如若是进行多重继承之后会出现只能找到最后一个父类的状况。

相关文章
相关标签/搜索