Extension Function (1): Extend - 面向对象网,web开发,Prototype,学习,对象 - 面向对象技术开发

面向对象技术开发

会员投稿 投稿指南 站长资讯通告:
您的位置: 首页 > Web开发 > Prototype > 正文

Extension Function (1): Extend

来源: www.bianceng.cn 阅读:

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.

本文出自 “技术源于专注” 博客,请务必保留此出处 http://mt830813.blog.51cto.com/7611383/1255653

查看本栏目更多精彩内容:http://www.bianceng.cn/webkf/prototype/

Tags:
相关文章列表: