原型链模式拓展2

40 篇文章 0 订阅
32 篇文章 0 订阅
<script>
        //在原型模式中,this常用的有两种情况:
        //在类中this.xxx=xxx;this->当前类的实例
        //某个方法中的this->看执行的时候"."前面是谁this就是谁
        //1)需要确定this的指向
        //2)把this替换成对应的代码
        //3)按照原型链查找机制,一步步查找
    function Fn() {
        this.x = 100;
        this.y = 200;
        this.getY=function () {
            console.log(this.y);
        }
    }
    Fn.prototype = {
        constructor:Fn,//一定记得重构时设置constructor
        y:300,
        getX: function(){
                 console.log(this.x);
        },
        getY: function () {
             console.log(this.y);
        }
    };
    var f = new Fn;
    f.getX();//->100;
    f.__proto__.getX();//->undefined//this是f.__proto__->console.log(f.__photo__.x)->undefined
    Fn.prototype.getX();//->undefined
    f.getY();//->200
    f.__proto__.getY();//->300
    //在内之类的原型上扩展我们的方法
    Array.prototype.myUnique = function () {
        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;

        }
        obj = null;
        return this;//目的是为了实现链式写法
    }
    var ary = [11,11,22,33];
    // ary.myUnique();
    // console.log(ary);
    //链式写法:执行完数组的一个方法可以紧接着执行下一个方法
    //原理:
    //首先sort方法是Array.prototype上的公有方法,而数组ary是Array这个类的一个实例,所以ary可以使用sort方法->只有数组才能使用Array原型上电仪的属性和方法
    //sort执行完成的返回值是一个排序后的"数组",可以继续执行reverse
    //reverse执行完成后的返回值也是一个数组,可以继续执行pop
    //pop执行完成的返回值是被删除的那个元素,不是一个数组
    //pop之后不可继续执行链式写法,继续执行会报错
    ary.sort(function (a,b) {
        return a - b;    
    }).reverse().pop();

    // ary.__proto__.myUnique();//IE下禁止使用__proto__
    Array.prototype.myUnique();//this-> Array.prototype.
    </script>
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值