The basic stone for writing good code is oo, and the most important feature for oo is implment.ide
This is why I choose write about implement as my first tech article.this
No more to say.Just share my core codeprototype
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.
code
Then we test the origin feature about extend in js.it
First we declare parent classio
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.console
as my comment in the code,there is a constructor, allow you write private method and public method.ast
But still can't declare private var.function
After we declare parent then we declare child and extends from parentclass
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.