zoukankan      html  css  js  c++  java
  • 数组解耦

    以前这么写递归,如果函数名改变的话,下面的调用就要跟着改。

    function cl(a) {
    	if(a) {
    		return 1
    	}else{
    		return cl(a - 1) * a
    	}
    }

    使用arguments解耦函数体和函数名

    function cl(a) {
    	if(a) {
    		return 1
    	}else{
    		return arguments.callee(a - 1) * a
    	}
    }

    使用call 和 apply

    1. 一般调用函数
    
    let fn = {
    	name: 'iamfn',
    	getName() {
    		console.log(this.name)
    	}
    }
    
    fn.getName()
    
    2. 使用call和apply是如何解耦函数
    apply():接收两个参数,第一个是函数执行的作用域,第二个是参数数组
    call():与apply类似,唯一不同的是接收参数时要一一列出这些参数。
    
    function sum(a, b, c) {
    	return a + b + c
    }
    sum.call(this, 1,2,3)
    sum.apply(this, [1,2,3])
    sum.apply(null, [1,2,3])
    
    3. 解耦对象,扩充函数的作用域。
    let animal = {
    	name: 'animal',
    }
    let cat = {
    	name: '小白'
    }
    let name = '全局'
    
    function sayName() {
    	console.log(this.name)
    }
    
    sayName() // ’全局‘
    
    sayName.call(cat) // '小白'
    
    sayName.apply(animal) // 'animal'
  • 相关阅读:
    ROS 学习遇到的问题记录(持续更新)
    09.07 jQuery 随意整理
    JavaScript 随意整理3
    JavaScript 随意整理2
    css 随意整理 08.08
    html 随意整理
    vue day2
    vue day1
    【copy】必备之常用正则表达式 By 其他博主
    note.js 笔记第二课
  • 原文地址:https://www.cnblogs.com/huangjunjia/p/13068171.html
Copyright © 2011-2022 走看看