apply和call 两个办法都能扭转函数外面 this 的指向,扭转后的函数 this 指向办法内的第一个参数。 apply和call 的次要区别在于,apply 前面向函数传递参数是借用的数组的模式,而 call 则应用逗号将参数分隔开即可。
示例:
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title></head><body> <script> //call 的办法会把函数的 this指向 指向函数的第一个参数,call传参的形式是逗号分隔开 const sm = { name: '蜘蛛侠', age: 25, dreams(truthName ,truthAge){ this.name = truthName this.age = truthAge } } sm.dreams('托比', 23) console.log(`sm的`,sm); const em = { name: '钢铁侠', age: 25 } sm.dreams.call(zjh , '小罗伯特唐尼' , 88) console.log(`em的`,em); //apply 的办法也会把 this指向 指向函数的第一个参数,和 call 不同的是, apply的参数是以数组的形式传递的 const today = { weather: '晴天', date: '5月9号', correct(weather,date){ this.weather = weather this.date = date } } today.correct('暴雨','5月10号') console.log('today', today); const tomorrow = { weather: '小雨', date: '不晓得' } today.correct.apply(tomorrow, ['大晴天', '5月中旬']) console.log('tomorrow' ,tomorrow); </script></body></html>
图示:
欢送指错!