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 就是当前类的实例
        // 某一个方法中的this->看执行的时候"."前面是谁 this 是谁
        // 1>需要先确定this的指向 (this是谁)
        // 2>把this换成对应的代码
        // 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 找共有的


        // 在内置类的圆形上拓展我们的方法
        Array.prototype.myUnique = function () {
            // this -> ary
            // 数组去重
            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);

        // 链式写法:执行完成数组的一个方法可以紧接着执行下一个方法
        // 原理:
        // ary为什么可以使用sort方法? 因为sort是Array.prototype上的,而数组是ary是Array这个类的一个实例,所以ary可以使用sort方法 数组才能使用array原型上的定义的属性和方法
        var ary2 = [12, 23, 23, 23, 13, 13, 14];
        // sort执行完成之后的返回值是一个排序后的"数组",可以继续执行reverse
        // reverse执行完成的返回值是一个数组,可以继续执行pop
        // pop执行完成的返回值是被删除的那个元素,不是一个数组了
        ary.sort(function (a,b) {
            return a - b ;
        }).reverse().pop();


    </script>  
 </body>
</html>
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容