js函数

74 阅读2分钟

arguments

概念:arguments是包含所有参数的伪数组,他的原型链没有正紧数组的共有属性

function fn(){
    console.log(arguments)
}  
fn(1,2,3)     // 传参伪数组 1,2,3

uTools_1672573145591.png

this

特点:1. 在没有任何条件下this默认指向window

function fn(){
    console.log(this)
}
fn()          //window
fn.call(1)    //Number{1}
  1. 只能用 call() 传参,而且 参数 会被自动转化成对象(JS 的糟粕),用'use strict'可以禁用这一特性
function fn(){
    'use strict'
    console.log(this)
}
fn.call(1)          // 1
  1. fn.call(xxx, 1,2,3) 第一个参数xxx传 this ,其他的传 arguments 微信截图_20230101215129.png

因此: this 是隐藏参数 arguments 是普通参数

  1. this的作用 :获取一个未知对象的引用供函数调用
let person = {
  name: 'frank',
  sayHi(this){
    console.log(`你好,我叫` + this.name)   // 你好,我叫 frank
  }
}
person.sayHi()

/*
person.sayHi()
相当于
person.sayHi(person)
然后 person 被传给 this 了(person 是个地址)
这样,每个函数都能用 this 获取一个未知对象的引用了
*/
  1. 调用方法

    1. person.sayHi()
    2. person.sayHi.call(person) // 以后都用这调用函数
  2. this 的两种使用方法

// 隐式传递
fn(1,2) // 等价于 fn.call(undefined, 1, 2)
obj.child.fn(1) // 等价于 obj.child.fn.call(obj.child, 1)
// 显示传递
fn.call(undefined, 1,2)
fn.apply(undefined, [1,2])
  1. bind 绑定 this

使用 bind 可以让 this 不被改变

function f1(p1, p2){
  console.log(this, p1, p2)
}
let f2 = f1.bind({name:'frank'})    // f2 就是 f1 绑定了 this 之后的新函数
f2() // 等价于 f1.call({name:'frank'})

bind 还可以绑定其他参数

let f3 = f1.bind({name:'frank'}, 'hi')
f3()   // 等价于 f1.call({name:'frank'}, hi)

函数调用方法

function.call(thisArg, arg1, arg2, ...) 

thisArg为要传的this值,没有时用undefined或null占位
如果这个函数处于非严格模式下,则指定为 null 或 undefined 时会自动替换为指向全局对象,原始值会被包装。

箭头函数

没有 arguments 和 this ,里面的 this 就是外面的 this ,也就是window

console.log(this) // window
let fn = () => console.log(this) 
fn() // window
// 就算你加 call 都没有
fn.call({name:'frank'}) // window