美文网首页
this & arguments

this & arguments

作者: _William_Zhang | 来源:发表于2018-09-23 17:00 被阅读1次
  • this 是隐藏的第一个参数,且一般是对象(如果不是对象,就显得很没有意义了)

      function f(){
          console.log(this)
          console.log(arguments)
      }
      f.call() // window
      f.call({name:'frank'}) // {name: 'frank'}, []
      f.call({name:'frank'},1) // {name: 'frank'}, [1]
      f.call({name:'frank'},1,2) // {name: 'frank'}, [1,2]
    

通过 .call 来调用函数,call 的第一个参数是 this ,如果不传,那默认是 window,如果传的参数不是对象,那么会自动转换为对象类型,总之,this必须是对象!!! [注意:是小写的 window ,但 chrome浏览器 犯jian,显示的却是大写的 Window]。

call 除了第一个参数外,后面的参数 都 属于 arguments ,如果不传参,那么 arguments 就是一个空数组 。arguments 是 一个 伪数组(只是形式和数组像,但不具备只有数组才有的一些方法)。

如果你不是用 call 来调用函数,直接 f() 。例如 f(1),那么这个 1 就会被放在 arguments 里 ;这时候的 this 还是 window ,虽然你只传了一个参数 1 。所以,要用 .call() ,不要 f(),因为f()对初学者不友好,。call()反而思路更清晰一些。

每个函数都有 return
如果你不写 return,就相当于写了 return undefined

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

    var person = {
        name: 'frank',
        sayHi: function(person){
            console.log('Hi, I am' + person.name)
        },
        sayBye: function(person){
            console.log('Bye, I am' + person.name)
        },
        say: function(person, word){
            console.log(word + ', I am' + person.name)
        }
    }
    person.sayHi(person)
    person.sayBye(person)
    person.say(person, 'How are you')
    
    // 能不能变成 
    person.sayHi()
    person.sayBye()
    person.say('How are you')
    
    // 那么源代码就要改了
    var person = {
        name: 'frank',
        sayHi: function(){
            console.log('Hi, I am' + this.name)
        },
        sayBye: function(){
            console.log('Bye, I am' + this.name)
        },
        say: function(word){
            console.log(word + ', I am' + this.name)
        }
    }
    // 如果你不想吃语法糖
    person.sayHi.call(person)
    person.sayBye.call(person)
    person.say.call(person, 'How are you')
    
    // 还是回到那句话:this 是 call 的第一个参数
    // this 是参数,所以,只有在调用的时候才能确定
    person.sayHi.call({name:'haha'})  // 这时 sayHi 里面的 this 就不是 person 了
    // this 真的很不靠谱
    
    // 新手疑惑的两种写法
    var fn = person.sayHi
    person.sayHi() // this === person
    fn()  // this === window
    

相关文章

网友评论

      本文标题:this & arguments

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