JS笔记

JSdeep(this&arguments&bi

2017-11-23  本文已影响6人  余生筑

call

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]

fn.call()发生了三件事

this

var person = {
    name: 'frank',
    sayHi: function(person){
        console.log( this.name)
    }
}

person.sayHi()//等效于person.sayHi.call(person)

person.sayHi.call({name:'Lisi'})
//Lisi,注意'person.'只是用于访问到sayHi所必需的一个前缀,当call无参数时,浏览器默认person为与sayHi相关联的对象

var fn=person.sayHi
fn.call(person)//frank
fn.call()//undefined

window.name='xxx'
fn.call()//等效于fn.call(window)

call与apply

function sum()
{
    var m=0
    for(var i=0;i<arguments.length;i++)
    {
        m+=arguments[i]
    }
    console.log(m)
}

var arr=[1,2,3,4.......100]

sum.call(undefined,arr[0],arr[1],arr[2].....arr[99])
//等效于sum.apply(undefined,arr)

bind与call

this.num = 9; 
var module = {
  num: 81
};

function getNum(n,m)
{
    console.log(this.num+n+m)
}
//下列四种写法等效
getNum.call(module,1,2)//84

getNum.bind(module)(1,2)//84

getNum.bind(module).call(module,1,2)//84

getNum.bind.call(getNum,module)(1,2)//84

bind的演变史

<html lang="en">
......
<body>
        <div id="div1">123</div>
</body>
</html>
<script>
    var module={
        name:'Lier',
        age:8
    }
    var fn=function()
    {
        console.log(this.name)
    }
   /*设置点击事件*/
</script>

假如我们想给div1设置监听事件,使得点击div1后控制台打印出"Lier",该如何实现?
我们可以这样写

document.getElementById('div1').onclick=function fm()
   {
    fn.call(module)
   }

js之父不喜欢fm这个函数,于是他用bind符号制定了一个等价规则以省略fm

   fn.bind(module)=function fm()
   {
    fn.call(module)
   }

现在我们可以这么写

document.getElementById('div1').onclick=fn.bind(module)
上一篇 下一篇

猜你喜欢

热点阅读