CallApplyBind-JavaScript

张开发
2026/4/21 18:47:23 15 分钟阅读

分享文章

CallApplyBind-JavaScript
const ferrari { brand: 法拉利, sound: 呜呜呜~, accelerate: function(speed, location) { // 这个 this 默认指向 ferrari console.log(${this.brand} 在 ${location} 飙到了 ${speed}码发出 ${this.sound}); } }; const wuling { brand: 五菱宏光, sound: 咯吱咯吱~ }; // 把 accelerate 的 this 强行指向 wuling ferrari.accelerate.call(wuling, 120, 秋名山); // 输出五菱宏光 在 秋名山 飙到了 120码发出 咯吱咯吱~ const params [80, 北京五环]; // apply 和 call 效果一样只是参数要装在 [数组] 里 ferrari.accelerate.apply(wuling, params); // 输出五菱宏光 在 北京五环 飙到了 80码发出 咯吱咯吱~ // bind 不会立刻执行它会返回一个“改装后”的新函数 const wulingRacing ferrari.accelerate.bind(wuling); console.log(--- 此时还没开始飙车 ---); // 哪怕等个三天三夜你调用这个新函数它依然记得 this 指向 wuling wulingRacing(150, 排水渠); // 输出五菱宏光 在 排水渠 飙到了 150码发出 咯吱咯吱~ 如果你直接写 wuling.accelerate(120, 秋名山)代码会直接报错因为五菱宏光对象里根本没有 accelerate 这个方法。箭头函数没有this这是理解一切的前提箭头函数本身根本就没有this绑定const user { name: 老弟, sayHi: function() { console.log(1. 当前this是, this.name); // 这里的 this 是 user setTimeout(function() { // 这个匿名函数是普通函数在 1 秒后由浏览器 window 调用 // window.name 是空的 console.log(2. 定时器里的this是, this.name); }, 100); } }; user.sayHi(); // 输出 1: 老弟 // 输出 2: undefined (或者报错因为 this 指向了全局 window) const user { name: 老弟, sayHi: function() { console.log(1. 当前this是, this.name); setTimeout(() { // 箭头函数我自己没 this我看看我爹是谁 // 它爹是 sayHi 方法sayHi 的 this 是 user // 所以这里的 this 也就是 user console.log(2. 箭头函数里的this是, this.name); }, 100); } }; user.sayHi(); // 输出 1: 老弟 // 输出 2: 老弟 (稳如老狗)Promise串行等待慢JavaScriptasync function loadData() { const categories await getCategories(); // 等 1 秒 const goods await getGoods(); // 再等 1 秒 // 总计 2 秒 } 并行出击快Promise.all 的魅力 JavaScript async function loadData() { // 两个请求同时发出 const [categories, goods] await Promise.all([getCategories(), getGoods()]); // 总计只需 1 秒取最慢的那个 }

更多文章