Extension Function (1): Extend

The basic stone for writing good code is oo, and the most important feature for oo is implment.

This is why I choose write about implement as my first tech article.

No more to say.Just share my core code

Function.prototype.Implement = function (parentType) {
    //check parent is exists and parent's type is able to implment
    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;
    }
}

There is the core code.

Then we test the origin feature about extend in js.

First we declare parent class

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

Recommand this way to declare class.

as my comment in the code,there is a constructor, allow you write private method and public method.

But still can't declare private var.


After we declare parent then we declare child and extends from parent

var child= function () {
    //constructor
}
child.prototype = (function () {
    //private
    return {
        SomeVar:"I'm the second generation"
        DoSomeStaff:function(){
           this.base.DoSomeStaff.call(this);//call parent's method
        }
    };
})();
//child extend from parent
child.Implement(parent)


Declare done. then we test.

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


You can see, this way to written is more fit high-level language's grammar and make your code more readable.

But still this way to written extend still can't multi extend.

the last parent will replace all previous parent.

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章