JS函数调用的5种模式

函数是经常会用的工具, 这里总结一下关于在 js 中的 5种函数调用的模式如下:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <script>
    // 函数调用5种模式

    // 1. 函数声明调用模式
    function add(a, b) {
      return a + b
    }

    // 2. 匿名函数调用模式
    var sum = function(a, b) {
      return a + b
    }
    console.log(sum(3, 5))

    var sub = function (a, b) {
      return a - b
    }

    console.log('add: ', add(3, 5))
    console.log('sub: ', sub(3, 5))

    // 3. 方法调用模式
    var obj = {
      name: 'youge',
      getName: function () {
        return this.name
      }
    }

    console.log(obj.getName())

    // 若在某个方法中返回的是函数对象本身 this 则可以进行链式调用
    var obj2 = {
      name: 'youge2',
      getName: function () {
        console.log(this.name)
      },
      setName(name) {
        this.name = name 
        return this
      }
    }

    obj2.setName('cj').getName()

    // 4. 构造器调用模式
    function Person(name) {
      this.name = name
    }
    // 函数定义在其原型上
    Person.prototype.getName = function () {
      return this.name
    }
    // 通过对象实例进行调用
    var youge = new Person('youge')
    console.log(youge.name)

    // 5. call(), apply函数调用模式
    function sum(a, b) {
      console.log(a + b) 
    }
    // 定义一个对象 dog, 当 sum 调用时, this 则会指向 dog
    var dog = {}
    sum.call(dog, 1, 2)
    sum.apply(dog, [1, 2])

  </script>
</body>
</html>
posted @ 2023-07-24 11:50  致于数据科学家的小陈  阅读(23)  评论(0编辑  收藏  举报