16-原型鏈模式拓展

<!DOCTYPE html>
<html lang="en">
 <head> 
  <meta charset="UTF-8" /> 
  <title>原型鏈模式(拓展-this和原型擴展)</title> 
 </head> 
 <body> 
  <script type="text/javascript">
        // 在原型模式中,this有兩種情況:
        // 在類中 this.xxx = xxx ; this 就是當(dāng)前類的實例
        // 某一個方法中的this->看執(zhí)行的時候"."前面是誰 this 是誰
        // 1>需要先確定this的指向 (this是誰)
        // 2>把this換成對應(yīng)的代碼
        // 3>按照原型鏈查找的機制
        function Fn() {
            this.x = 100;
            this.y = 200;
            this.getY = function () {
                console.log(this.y);
            }
        }
        Fn.prototype = {
            constructor :Fn,
            y:300,
            getX:function () {
                console.log(this.x); // this-> f
            },
            getY:function () {
                console.log(this.y);
            }
        };
        var f = new Fn;
        f.getX(); // console.log(f.x) 100;
        f.__proto__.getX(); // this是 f.__proto  -> console.log(f.__proto__.x); undefined
        Fn.prototype.getX(); // Fn.prototype.getX() -> undefined
        f.getY(); // 200 找私有的
        f.__proto__.getY(); // 300 找共有的


        // 在內(nèi)置類的圓形上拓展我們的方法
        Array.prototype.myUnique = function () {
            // this -> ary
            // 數(shù)組去重
            var obj = {};
            for (var i = 0; i < this.length;i++) {
                var cur = this[i];
                if (obj[cur] == cur) {
                    this[i] = this[this.length -1];
                    this.length--;
                    i--;
                    continue;
                }
                obj[cur] = cur;
            }
        }
        var ary = [];
        ary.myUnique(); // ary
//        ary.__proto__.myUnique(); IE下屏蔽
        Array.prototype.myUnique(); // this-> Array.prototype
        var ary = [12, 23, 23, 23, 13, 13, 14];
        ary.myUnique();
        console.log(ary);

        // 鏈?zhǔn)綄懛?執(zhí)行完成數(shù)組的一個方法可以緊接著執(zhí)行下一個方法
        // 原理:
        // ary為什么可以使用sort方法? 因為sort是Array.prototype上的,而數(shù)組是ary是Array這個類的一個實例,所以ary可以使用sort方法 數(shù)組才能使用array原型上的定義的屬性和方法
        var ary2 = [12, 23, 23, 23, 13, 13, 14];
        // sort執(zhí)行完成之后的返回值是一個排序后的"數(shù)組",可以繼續(xù)執(zhí)行reverse
        // reverse執(zhí)行完成的返回值是一個數(shù)組,可以繼續(xù)執(zhí)行pop
        // pop執(zhí)行完成的返回值是被刪除的那個元素,不是一個數(shù)組了
        ary.sort(function (a,b) {
            return a - b ;
        }).reverse().pop();


    </script>  
 </body>
</html>
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容