美文网首页
2019-05-14 this&arguments

2019-05-14 this&arguments

作者: tsl1127 | 来源:发表于2019-05-14 17:00 被阅读0次

    this 是隐藏的第一个参数,且一般是对象
    function f(){
    console.log(this)
    console.log(arguments)
    }
    f.call() // window []
    f.call({name:'frank'}) // {name: 'frank'}, [] 第一项是this,后面的是arguments
    f.call({name:'frank'},1) // {name: 'frank'}, [1]
    f.call({name:'frank'},1,2) // {name: 'frank'}, [1,2]
    arguments是个伪数组


    image.png

    this 为什么必须是对象
    因为 this 就是函数与对象之间的羁绊


    image.png

    假如这里传的是个数字10,也会被new Number(10)下,变成数字对象


    image.png
    image.png
    // 新手疑惑的两种写法
    var fn = person.sayHi

    person.sayHi() // this === person
    fn() // this === window

    fn.call(asThis, p1,p2) 是函数的正常调用方式
    当你不确定参数的个数时,就使用 apply
    fn.apply(asThis, params)

    相关文章

      网友评论

          本文标题:2019-05-14 this&arguments

          本文链接:https://www.haomeiwen.com/subject/hlteaqtx.html