bind、call、apply

含义:  都是改变函数运行时的this指向。

 

apply方法:

1、apply接受两个参数,第一个参数是this的指向,第二个参数是函数接受的参数,以数组的形式传入,且当第一个参数为null、undefined的时候,默认指向window(在浏览器中)

2、使用apply方法改变this指向后原函数会立即执行,且此方法只是临时改变this指向一次。

 

var obj = {
  name: 1,
  say: function(age,sex) {
    console.log(this.name,age,sex)  
   }  
}

var say = obj.say

say.apply(obj,[12,'男'])

 

 

call方法:

1、call接受两个参数,第一个参数是this的指向,第二个参数是函数接受的参数,以参数列表的形式传入,且当第一个参数为null、undefined的时候,默认指向window(在浏览器中)

2、使用call方法改变this指向后原函数会立即执行,且此方法只是临时改变this指向一次。

 

var obj = {
  name: 1,
  say: function(age,sex) {
    console.log(this.name,age,sex)  
   }  
}

var say = obj.say

say.call(obj,12,'男')

bind方法:

1、bind接受两个参数,第一个参数是this的指向,第二个参数是函数接受的参数,以参数列表的形式传入,(但可以分多次传入)且当第一个参数为null、undefined的时候,默认指向window(在浏览器中)

2、使用bind方法改变this指向后原函数不会立即执行,且此方法永久改变this指向。

var obj = {
  name: 1,
  say: function(age,sex) {
    console.log(this.name,age,sex)  
   }  
}

var say = obj.say

var s = say.bind(obj,12)

s('男')

 

模拟call方法:

 

Function.prototype.myCall = function(context) {
 if(typeof this  !== 'function') throw new TypeError('not function')
  context = context || window
  context.fn = this
  let args = [...arguments].slice(1) //去掉context
  let result = context.fn(...args)  
  delete context.fn
  return result
}

 

模拟apply方法:

Function.prototype.myApply = function(context,args = []) {
 if(typeof this  !== 'function') throw new TypeError('not function')
  context = context || window
  context.fn = this
  let result = context.fn(...args)  
  delete context.fn
  return result
}

 

模拟bind方法:

Function.prototype.myBind = function(context) {
 if(typeof this  !== 'function') throw new TypeError('not function')
  context = context || window
  context.fn = this
let args = [...arguments].slice(1) //去掉context
  return function (args) {
  return context.fn(...args)
 }
}

 

posted on 2020-04-29 14:19  斜杠人生  阅读(241)  评论(0编辑  收藏  举报

导航