JS的一些知识点

281 阅读5分钟

学习了coderwhy的JavaScript高级语法视频课的笔记

如有错误或者不合适的地方,敬请见谅,欢迎指出和拓展,谢谢各位了

一、JS简单实现call、apply和bind

注意:我们的实现是练习函数、this、调用关系,不会过度考虑一些边界情况

  1. call
// 1.简单实现call
Function.prototype.hycall = function (thisArg, ...args) {
  // this的隐式绑定,获取到调用函数(foo函数)
  var fn = this
  
  //   thisArg不为空则转化为对象,否则为window
  thisArg = thisArg ? Object(thisArg) : window
  
  // 主要是为下一步改变调用函数(foo函数)this的指向(为thisArg)
  thisArg.fn = fn
  
  // 调用foo函数,foo函数this指向thisArg
  var result = thisArg.fn(...args)
  
  // 由于call使用c++实现,这里是JavaScript实现,所以存在{fn: ƒ}
  delete thisArg.fn

  return result
}

function foo(num1, num2) {
  console.log(this)
  return num1 + num2
}

console.log(foo.hycall({}, 10, 20)) //30
console.log(foo.call({}, 10, 20)) //30

image.png

  1. apply
// 2.简单实现apply
Function.prototype.hyapply = function (thisArg, args) {
  var fn = this
  
  thisArg = thisArg ? Object(thisArg) : window
  
  thisArg.fn = fn
  
  // 没有参数的情况下,直接调用
  if (!args) {
    thisArg.fn()
  } else {
    var result = thisArg.fn(...args)
  }
  
  delete thisArg.fn
  
  return result
}

function foo(nu1, num2) {
  console.log(this)
  return nu1 * num2
}

console.log(foo.hyapply({}, [10, 20]))//200
console.log(foo.apply({}, [10, 20]))//200

image.png

  1. bind
// 3、简单实现bind
Function.prototype.hybind = function (thisArg, ...args) {
  var fn = this
  thisArg = thisArg ? Object(thisArg) : window
  thisArg.fn = fn

  // 因为bind返回的是一个函数
  return function (...args2) {
    //   先后传参的拼接
    var newargs = [...args, ...args2]
    //   最后调用返回结果
    return thisArg.fn(...newargs)
  }
}

function foo(num1, num2) {
  console.log(this)
  return num1 + num2
}

var hyfn = foo.hybind({}, 10)//return function
console.log(hyfn(20))//30

console.log('------------')

var fn = foo.bind({}, 10)//return function
console.log(fn(20))//30

image.png

二、arguments

  1. arguments 是一个对应于传递给函数的参数的类数组(array-like)对象
function foo(x, y, z) {
  console.log(arguments) //[Arguments] { '0': 10, '1': 20, '2': 30 }
}
foo(10, 20, 30)
  1. array-like意味着它不是一个数组类型,而是一个对象类型
  • 但是它却拥有数组的一些特性,比如说length,比如可以通过index索引来访问;
  • 但是它却没有数组的一些方法,比如forEach、map等;
function foo(x, y, z) {
  console.log(arguments) //[Arguments] { '0': 10, '1': 20, '2': 30 }
  console.log(arguments.length) //3
  console.log(arguments[0]) //10
}
foo(10, 20, 30)
  1. arguments转成array
function foo(x, y, z) {
  // 方式一
  var arr = []
  for (var i = 0; i < arguments.length; i++) {
    arr.push(arguments[i])
  }
  console.log(arr) //[ 10, 20, 30 ]

  // 方式二
  var arr2 = Array.prototype.slice.call(arguments)
  var arr22 = [].slice.call(arguments)
  console.log(arr2) //[ 10, 20, 30 ]
  console.log(arr22) //[ 10, 20, 30 ]

  // 方式三:ES6之后
  const arr3 = Array.from(arguments)
  const arr33 = [...arguments]
  console.log(arr2) //[ 10, 20, 30 ]
  console.log(arr33) //[ 10, 20, 30 ]
}
foo(10, 20, 30)
  1. 箭头函数是不绑定arguments的,所以我们在箭头函数中使用arguments会去上层作用域查找

三、JavaScript纯函数

  1. 函数式编程中有一个非常重要的概念叫纯函数,JavaScript符合函数式编程的范式,所以也有纯函数的概念
  • 判断是否是纯函数的简单总结:
    • 确定的输入,一定会产生确定的输出(返回值)。也就是无论调用函数多少次,主要参数不变,返回的值都是一样的结果,而且返回的值不受函数外界的值所影响;
    • 函数在执行过程中,不能产生副作用(在计算机科学中,也引用了副作用的概念,表示在执行一个函数时,除了返回函数值之外,还对调用函数产生了附加的影响,比如修改了全局变量,修改参数或者改变外部的存储)。
  1. 纯函数的案例
  • 我们来看一个对数组操作的两个函数:
    • slice:slice截取数组时不会对原数组进行任何操作,而是生成一个新的数组;
    • splice:splice截取数组, 会返回一个新的数组, 也会对原数组进行修改;
    • slice就是一个纯函数,不会修改传入的参数。
  1. 纯函数的优势
  • 为什么纯函数在函数式编程中非常重要呢?
    • 因为你可以安心的编写和安心的使用;
    • 你在写的时候保证了函数的纯度,只是单纯实现自己的业务逻辑即可,不需要关心传入的内容是如何获得的或 者依赖其他的外部变量是否已经发生了修改;
    • 你在用的时候,你确定你的输入内容不会被任意篡改,并且自己确定的输入,一定会有确定的输出。

四、JavaScript柯里化

  1. 柯里化也是属于函数式编程里面一个非常重要的概念。
  • 判断是否是纯函数的简单总结:
    • 只传递给函数一部分参数来调用它,让它返回一个函数去处理剩余的参数,这个过程就称之为柯里化。
function add1(x, y, z) {
  return x + y + z
}

console.log(add1(10, 20, 30))//60

// 柯里化处理函数
function add2(x) {
  return function (y) {
    return function (z) {
      return x + y + z
    }
  }
}

console.log(add2(10)(20)(30))//60
  1. 让函数的职责单一 在函数式编程中,我们其实往往希望一个函数处理的问题尽可能的单一,而不是将一大堆的处理过程交给一个函数来处理,那么我们就可以将每次传入的参数在单一的函数中进行处理,处理完后再下一个函数中再使用处理后的结果。
  2. 柯里化的复用 使用柯里化的场景是可以帮助我们可以复用参数逻辑:
function makeAdder(x) {
  return function (y) {
    return x + y
  }
}

var add = makeAdder(10)
console.log(add(20))//30
console.log(add(30))//40
  1. 自动柯里化
function hycurry(fn) {
  return function (...args) {
    // fn.length就是函数参数的个数
    if (args.length >= fn.length) {
      // 之所以使用apply,是因为要保证调用函数(add)使用apply时this绑定一致
      return fn.apply(this, args)
    } else {
      return function (...args2) {
        return fn.apply(this, [...args, ...args2])
      }
    }
  }
}

function foo(x, y) {
  return x + y
}

var add = hycurry(foo)
console.log(add(10, 20)) //30
console.log(add(20)(30)) //50
  1. 理解组合函数 组合(Compose)函数是在JavaScript开发过程中一种对函数的使用技巧、模式:比如我们现在需要对某一个数据进行函数的调用,执行两个函数fn1和fn2,这两个函数是依次执行的,那么如果每次我们都需要进行两个函数的调用,操作上就会显得重复,可以将这两个函数组合起来,自动依次调用,这个过程就是对函数的组合,我们称之为组合函数(Compose Function)。
1.简单实现
function add(num) {
  return num + 1
}

function double(num) {
  return num * 2
}

function compose(fn1, fn2) {
  return function (num) {
    return fn1(fn2(num))
  }
}

var composeFN = compose(add, double)
console.log(composeFN(10))//22

2.复杂实现
function add(num) {
  return num + 1
}

function double(num) {
  return num * 2
}

function compose(...fns) {
  //判断传入的参数是否全部是函数
  var l = fns.length
  for (var i = 0; i < l; i++) {
    if (typeof fns[i] !== 'function') {
      throw new TypeError('参数要是函数')
    }
  }

  return function (...args) {
    var index = 0
    //先执行第一个拿到值,如果l===0,也就是没有传入函数参数,返回args数组
    var result = l ? fns[index].apply(this, args) : args
    //拿到第一次的值后,再执行下一个函数
    while (++index < l) {
      result = fns[index].call(this, result)
    }
    return result
  }
}

var composeFN = compose(add, double)
console.log(composeFN(10)) //22

五、with语句

  • with语句 扩展一个语句的作用域链。
  • 不建议使用with语句,因为它可能是混淆错误和兼容性问题的根源。
var obj = {
  name: 'hello world',
  age: 18
}

with (obj) {
  console.log(name) //hello world
  console.log(age) //18
}

六、eval函数

  • eval是一个特殊的函数,它可以将传入的字符串当做JavaScript代码来运行。
//注意加分号
var evalString = 'var message ="hello world";console.log(message)'

eval(evalString) //hello world
  • 不建议在开发中使用eval
    • eval代码的可读性非常的差(代码的可读性是高质量代码的重要原则);
    • eval是一个字符串,那么有可能在执行的过程中被刻意篡改,那么可能会造成被攻击的风险;
    • peval的执行必须经过JS解释器,不能被JS引擎优化。

七、认识严格模式

  1. 在ECMAScript5标准中,JavaScript提出了严格模式的概念(Strict Mode):
  • 严格模式很好理解,是一种具有限制性的JavaScript模式,从而使代码隐式的脱离了 ”懒散(sloppy)模式“
  • 支持严格模式的浏览器在检测到代码中有严格模式时,会以更加严格的方式对代码进行检测和执行。
  1. 严格模式对正常的JavaScript语义进行了一些限制:
  • 严格模式通过抛出错误来消除一些原有的静默(silent)错误(比如true.sum=12);
  • 严格模式让JS引擎在执行代码时可以进行更多的优化(不需要对一些特殊的语法进行处理);
  • 严格模式禁用了在ECMAScript未来版本中可能会定义的一些语法(比如保留字的使用);
  1. 开启严格模式
  • 那么如何开启严格模式呢?严格模式支持粒度话的迁移:
    • 可以支持在js文件中开启严格模式;
    • 也支持对某一个函数开启严格模式。
  • 严格模式通过在文件或者函数开头使用 "use strict" 来开启。
  1. 严格模式限制的几种情况
  • 无法意外的创建全局变量;
  • 严格模式会使引起静默失败(silently fail,注:不报错也没有任何效果)的赋值操作抛出异常;
  • 严格模式下试图删除不可删除的属性;
  • 严格模式不允许函数参数有相同的名称;
  • 不允许0的八进制语法;
  • 在严格模式下,不允许使用with;
  • 在严格模式下,eval不再为上层引用变量;
  • 严格模式下,this绑定不会默认转成对象。