• 2.6原型链模式扩展-this和原型扩展,链式写法


    1.在原型模式中,this常用的有两种情况:

      1)在类中this.xxx = xxx; this是当前类的实例

      2)在某一个方法中的this,看执行的时候“.”前面是谁this就是谁,不管前面有多长,this就是多长

        a)需要先确定this指向(this是谁)

        b)把this替换成对应得代码

        c)按照原型链查找的机制,一步步的查找结果

    function Fn() {
    
      this.x = 100;
    
      this.y = 200;
    
      this.getY = function(){}
    
    }
    
    Fn.prototype = {
    
      constructor: Fn,
    
      y: 300,
    
      getX: function(){
    
        console.log(this.x)
      },
    
      getY: function(){
    
        console.log(this.y)
      }
    
    }
    
    var f = new Fn;
    
    f.getX(); // 100 console.log(f.x)-> 100
    f.__proto__.getX();//->this是f.__proto__->console.log(f.__proto__.x)->undefined,
    f.__proto__.x忽略私有的直接查询公有的,公有的上面没有x所以值为undefined

    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

      }

      obj = null

      return this; // 目的是为了实现链式写法

    }

    var ary = [12,23,23,13,12,23,13]

    链式写法:执行完成数组的一个方法可以紧接着执行下一个方法

      原理:

        ary为什么可以使用sort方法,因为sort是Array.prototype上的公有的方法,而数组ary是Array这个类的一个实例,所以ary可以使用sort方法 ->数组才能使用Array原型上定

        义的属性和方法

      // sort执行完成的返回值是一个排序后的“数组”

      // reversez执行完成的返回值是一个数组,可以继续执行pop

      // pop执行完成的返回值是被删除的那个元素,不是一个数组了,在执行数组的方法就会报错

    ary.sort(function(a,b){

      return a - b;

    }).reverse().pop();

    思考:

      

    (5).plus(10).reduce(2)   5+10-2

    Number.prototype.plus=function(n){}

    Number.prototype.reduce=function(n){}

  • 相关阅读:
    .net core读取appsettings.config中文乱码问题
    vs2017错误:当前页面的脚本发生错误
    VS Code中无法识别npm命令
    Visual Studio报错/plugin.vs.js,行:1074,错误:缺少标识符、字符串或数字
    记录一次在生成数据库服务器上出现The timeout period elapsed prior to completion of the operation or the server is not responding.和Exception has been thrown by the target of an invocation的解决办法
    Java集合框架
    java hash表
    Java Dictionary 类存储键值
    java数据结构 栈stack
    java封装
  • 原文地址:https://www.cnblogs.com/z-dl/p/8927094.html
Copyright © 2020-2023  润新知