es6面向对象

什么是面向对象

机器语言->汇编语言->低级语言(面向过程)->高级语言(面向对象)->框架->api

面向对象 : 把一些公共的东西封装起来 , 通过new出来的对象直接调用就行

#面向对象的知识点-call

#类和构造函数

image-20200305101659985

#

#改变this指向

#call 是什么

 function fn(...args) {
    console.log(this, args);
  }

  /*
  * fn 放在对象中 对象.fn()可以调用这个方法 此时this指向该对象
  * */

  /* 
  * 改变this指向 js提供三个方法  call apply bind
  * 函数.call(参数1:想改变成的this, 后面的参数 会依次传递到原函数中)
  * 函数.apply(参数1:想改变成的this, 第二个参数是一个数组)
  * 函数.apply(参数1:想改变成的this,后面的参数 会依次传递到原函数中) 
  		特点: 不会立即执行, 会返回一个新的函数 执行这个函数就可以传递
  *
  * */
  let arr = [1, 2, 3];
  fn.call(arr, '小耿', '小杨', '小候',);
 

#call的应用-类型判断

/*
* 所以 对于类型检测 最好采用下面方式:
* */
const isType = type => target => `[object ${type}]` === Object.prototype.toString.call(target);

const isArray = isType("Array");
const isObject = isType("Object");
const isRegExp = isType("RegExp");
const isNull = isType("Null");
console.log(isArray({}));
 

#apply

  function fn1(...args) {

    console.log(this, args);
  }

  let obj = {name: '张三'};

  //call 传参可以传无限个  apply 传参用数组的方式传递
  fn1.apply(obj, ['1', '2','fsfs']);
 

#bind

  function fn(...args) {
    console.log(this,args);//['hello',{name: 'name'},'1,2,3']
  }

  let arr = [1, 2, 3];

  //bind也可以改变this指向  但是不会立即执行
  //此时 bind返回一个新的函数
  //如果想传参的话 通过fn.bind 或者 返回的新的函数中传参
  const newFn = fn.bind(arr, 'hello',{name: 'name'});
  newFn('1,2,3');
 

#面向对象的知识点-prototype

#prototype的本质

对象.__proto__ === .prototype  解释过来就是 类可以调用的属性或者方法都在对象的原型上
1

#es6中面向对象

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
</head>
<body>
<script>

  /*
  * es5中的面向对象
  *
  * */

  let arr = new Array(1, 2, 3);

  //1: 对象(实例)  = new 类/构造函数()


  //Person 大写

  //Person 类 === 构造函数
  //es中 类 === 构造函数
  //类: 只要有 new new后面跟着的就是类
  //构造函数 : 通过参数 可以传递到函数本身的this身上


  function Person(name,age) {
    //this === person // true
    this.name = name;
    this.age = age;

    this.fn = function () {
      console.log(this === person);

    }
  }

  //new 得到了实例
  let person = new Person('张三',20);//对象
  console.log(person.name);
  console.log(person.age);
  console.log(person.fn());


</script>
</body>
</html>
 

#super : 父类的原型

class Person {
    constructor(name) {
      this.name = name;
      console.log(this.name);
    }

    getName() {
      console.log('父类的getName');
    }
  } 
class Man extends Person {
    constructor(props) {
      super(props);
       super.getName();//调用父类的getName()
    }
 }
 

#es6实现完整的继承

 class Person {
    constructor(name) {
      this.name = name;
      console.log(this.name);
    }

    getName() {
      console.log('父类的getName');
    }
  }

  class Man extends Person {
    constructor(props) {
      super(props);

    }
    getName() {
      console.log('子类的getName')
    }

    getSuperName() {
      super.getName();

      console.log(Person.prototype.getName === super.getName);

    }

  }

  new Man('小明').getSuperName();

 

#面向对象-小球案例

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
  <style>

    .circle {
      /* 40px;*/
      /*height: 40px;*/
      border-radius: 50%;
      /*background-color: #d14596;*/
      position: absolute;
    }

    .rect {
      position: absolute;
    }
  </style>
</head>
<body>
<div id="box">
  <button id="btnCircle">随机生成小球</button>
  <button id="btnRect">随机生成方块</button>
</div>

<script>
  btnCircle.onclick = function () {
    // 面向函数
    // let oCircle = document.createElement('div')
    // oCircle.classList.add('circle');
    // box.appendChild(oCircle);

    // 面向对象
    // 创建一个对象  class
    new Circle();
  };
  btnRect.onclick = function () {
    new Rect();
  };

  class Graph{
    random(min, max) {
      return Math.floor(Math.random() * (max - min) + min);
    }

    randomColor() {
      //# 1-9 + abcdef
      //#1efc4d
      const letters = ['a','b','c','d','e','f'];
      const strs = [...letters];
      for (let i = 0; i < 10; i++) {
        strs.push(i + '');
      }
      // console.log(strs);
      //#1efc4d
      let i = 0;
      let colorStr = '#';
      while (i < 6) {
        //随机的下标
        let index = this.random(0, strs.length);
        colorStr += strs[index];
        i++;
      }
      // console.log(colorStr);
      return colorStr;
    }
  }

  class Circle extends Graph{
    /*
    * 构造函数可以省略
    *
    * 小球:属性 : 大小 小球的颜色 位置
    *     方法 : 功能 创建小球/随机数/随机颜色/拖拽
    *
    * */
    constructor() {
      /*
      * 属性 : 小球本身 颜色 位置
      * */
      /*大小*/
      super();
      this.r = this.random(10,100);
      this.x = this.random(10,1200);
      this.y = this.random(10,500);
      this.color = this.randomColor();
      //调用创建小球的方法
      this.createEl();
    }

    /*
     * 方法 : 功能
     * */

    /*创建小球*/
    createEl() {
      let {r, color, x, y} = this;
      this.circle = document.createElement('div');
      this.circle.classList.add('circle');
      this.circle.style.width = `${r * 2}px`;
      this.circle.style.height = `${r * 2}px`;
      this.circle.style.backgroundColor = `${color}`;
      this.circle.style.left = `${x}px`;
      this.circle.style.top = `${y}px`;
      box.appendChild(this.circle);
    }
  }

  class Rect extends Graph{
    /*
    * 构造函数可以省略
    *
    * 小球:属性 : 大小 小球的颜色 位置
    *     方法 : 功能 创建小球/随机数/随机颜色/拖拽
    *
    * */
    constructor() {
      super();
      /*
      * 属性 : 小球本身 颜色 位置
      * */
      /*大小*/
      this.r = this.random(10,100);
      this.x = this.random(10,1200);
      this.y = this.random(10,500);
      this.color = this.randomColor();
      //调用创建小球的方法
      this.createEl();
      this.drag();
    }

    /*
     * 方法 : 功能
     * */

    /*创建小球*/
    createEl() {
      let {r, color, x, y} = this;
      this.circle = document.createElement('div');
      this.circle.classList.add('rect');
      this.circle.style.width = `${r * 2}px`;
      this.circle.style.height = `${r * 2}px`;
      this.circle.style.backgroundColor = `${color}`;
      this.circle.style.left = `${x}px`;
      this.circle.style.top = `${y}px`;
      this.circle.style.zIndex = '0';
      box.appendChild(this.circle);
    }
    random(min, max) {
      return Math.floor(Math.random() * (max - min) + min);
    }

    drag() {
      let {circle} = this;
      let {zIndex} = circle.style;
      circle.onmousedown = function (ev) {
        // console.log(ev);
        document.onmousemove = function (event) {
          console.log(event);
        };
        document.onmouseup = function () {

        }
      }
    }

  }

</script>
</body>
</html>
 

image-20200306114412641

#es6 中数组常用方法

#静态方法

#Array.from(): 将一个伪数组转换成数组

 /*
  * 数组的静态方法
  * Array.from  将一个非数组-->数组  只能将伪数组变成数组
  * Array.isArray  判断一个变量是不是数组
  * */

  /*
  * 将一个非数组--》数组  Array.prototype 成员方法  Array.方法 静态方法
  * Array.isArray() : 只能将伪数组变成数组  [下标]
  * */
  let newArr = Array.from('abc');
  console.log(newArr);
  console.log(Array.from(document.getElementsByTagName('li')));
  console.log(Array.from(123));
  // console.log(Array.from(undefined));
  // console.log(Array.from(null));
  console.log(Array.from({a:1,b:2}));
  console.log(Array.from([1,2,3]));
 

#Array.is(): 判断是不是一个数组

  //判断一个变量是不是数组
  //typeof arr // object  这种局限性在于 引用类型通过typeof都会识别成 object
  //这种方式就是专门用来判断是不是数组的
  console.log(Array.isArray({})); 
 

#成员方法

这里面咱们主要是提出es6中给我们提供的一些数组的常用方法

我们首先回顾es5中有哪些常用方法

push / pop / shift / unshift / reserve / sort/ join/ concat
1

回顾一下还记得其中的用法吗

#es6中数组新增常用的方法

  • arr.forEach()

  • arr.map()

  • arr.every()

  • arr.filter()

  • arr.reduce()

  • arr.some()

  • arr.find()

  • arr.findIndex()

    这些方法的共同特点是参数都是回调函数其中除了reduce之外别剩余的参数的回调函数都(item,index,arr)=>{} 其中 item为数组每一项 index为数组下标 arr为当前数组

    接下来我们一个一个看

#forEach

  /*
  * arr.forEach((item可写可不写,index可写可不写,arr可写可不写)=>{})
  *
  * 特点: 不能打断 比如 break continue 都不能用
  *   return 也不好使
  * */

  let arr = [1, 2, 3];
  arr.forEach((item,index,arr)=>{
    //item : 数组中的每一个元素
    //index: 下标
    //arr : 数组本身
    console.log(item, index, arr);
    // if (index === 1) {
    //   return;
    // }
  })
 
let arr = [1, 2, 3, 4];
  /*
  * 参数 : 函数 每一个我们想要的参数 都在函数的参数里面
  * 没有返回值
  * */
  let newArr = arr.forEach((item, index, arr) => {
    console.log(item);
  });
  console.log(newArr);
 

#map

  let arr2 = [{name: '小候', age: 11},
    {name: '小靳', age: 12},
    {name: '小闫', age: 13}, {name: '小杨', age: 14}, {
      name: '小袁',
      age: 21
    }, {name: '小赵', age: 22}, {name: '小兴', age: 23}, {name: '小康', age: 24}, {name: '小邵', age: 24}];
  /*
  * map:遍历
  * 参数 : 是一个函数 每一个我们想要的参数 都在函数的参数里面
  * 返回值 新的数组  newArray每次push的值 是map里面的返回值
  * */

  newArray = arr2.map((item, index, arr) => {
    return ++item.age + 50;
  });
  console.log(newArray);
 

#some

  /*
  * some: 只要回调函数有某一个返回条件满足 就返回true
  * */
  flag = arr2.some(item => item.age > 20);
  console.log(flag);
 

#filter

  /*
  * filter : 机制和forEach  作用是:过滤
  * 返回值  : 返回新的数组 回调函数中返回的条件决定新的数组的元素
  * */
  newArr = arr2.filter((item, index) => {

    //条件一旦满足 newArr就会push当前item
    return item.age > 20;
  });
  console.log(newArr);
  console.log(`可以看电影的成员有:`);
  newArr.forEach(item => console.log(`${item.name}`));
 

#reduce

  /*
  * reduce 面试常客
  *
  * 参数介绍:
  * prev:  如果第一次循环 prev是数组里面的第一个元素
  *        从第二次开始循环 prev是上一次回调函数的返回值
  *
  * next:  始终代表 下一次循环的元素
  *
  * */

  [1, 2, 3, 4, 5].reduce((prev, next) => {
    //1 , 2 第一次
    //3 , 3 第二次
    //6 , 4 第三次
    console.log(prev, next);
    return prev + next;
  });

  /*
  * 常用      forEach  map   filter some
  * 不太常用 : find    every  reduce findIndex
  * */
 

#不常用方法

  • find
  • findIndex
  • every

#find和findIndex

  /*
  * find:机制 forEach
  * 从数组中查找到符合条件的元素, 返回一个我们查找到的元素在回调函数中返回我们查找的条件的第一个成员
  * */
  arr2 = [{name: '小候', age: 11},
    {name: '小靳', age: 12},
    {name: '小闫', age: 13}, {name: '小杨', age: 14}, {
      name: '小袁',
      age: 21
    }, {name: '小赵', age: 22}, {name: '小兴', age: 23}, {name: '小康', age: 24}, {name: '小邵', age: 24}];

  let has = arr2.find(item => {
    return item.age > 20;
  });
  // console.log(num);
  if (has) {//元素 / undefined
    console.log('终于找到你,还好我没放弃');
  } else {
    console.log('终于我们还是擦肩儿过');
  }

  let index = arr2.findIndex(item => item.age === 11);
  //如果没找到 返回-1 如果找到了 返回当前数组的下标
  console.log('findIndex', index);
 

#every

  /*
  * every : 每一个都符合条件 只要有一个不符合条件 返回false
  * */
  let flag = arr2.every((item, index) => {
    // return typeof item.age === 'number';
    return item.age > 20;
  });

  console.log(flag);
原文地址:https://www.cnblogs.com/yzy521/p/14132162.html