首頁  >  文章  >  php教程  >  一個小巧的Class方案

一個小巧的Class方案

高洛峰
高洛峰原創
2016-11-30 17:01:451186瀏覽

(function(){
    function Extend(func,proto){
        func.prototype.__proto__=proto.prototype;
        Object.defineProperty(func.prototype,"proto",{
            value: proto.prototype
        });
    }
    function Super(func,method){
        if(!method) method='constructor';
        return func.prototype.__proto__[method];
    }
    window.Extend=Extend;
    window.Super=Super;
})();

在處理super的super時候遇到了死循環:

this.super-->this.proto.constructor(){this.super}-->this.proto.constructor。 。 。

後來直接用了上面程式碼中的辦法,不想整得太複雜(就是不會。。)

(function(){
    function AAA(name){
        this.name=name;
    }
    function BBB(name){
        Super(BBB).call(this,name);
    }
    Extend(BBB,AAA);
    function CCC(name,age){
        Super(CCC).call(this,name);
        this.age=age;
    }
    Extend(CCC,BBB);
    var c=new CCC('ccc',18);
    console.log(c);
})();

然後不想污染Function,只能污染window了。 。 。

話說放在Function裡面是不是要好用些?

(function(){
    Function.prototype.Extend=function(proto){
        this.prototype.__proto__=proto.prototype;
    }
    Function.prototype.Super=function(method){
        if(!method) method='constructor';
        return this.prototype.__proto__[method];
    }
})();
(function(){
    function AAA(name){
        this.name=name;
    }
    function BBB(name){
        BBB.Super().call(this,name);
    }
    BBB.Extend(AAA);
    function CCC(name,age){
        CCC.Super().call(this,name);
        this.age=age;
    }
    CCC.Extend(BBB);
    var c=new CCC('ccc',18);
    console.log(c);
})();


陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn