溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

怎么修改Vue.js this的指向

發(fā)布時間:2021-11-05 14:21:35 來源:億速云 閱讀:749 作者:iii 欄目:web開發(fā)

這篇文章主要講解了“怎么修改Vue.js this的指向”,文中的講解內容簡單清晰,易于學習與理解,下面請大家跟著小編的思路慢慢深入,一起來研究和學習“怎么修改Vue.js this的指向”吧!

修改 this 的指向可通過 apply、call、bind 這三個函數中的任意一個實現。那這三個函數是誰的方法呢?

在 MDN 中我查到了:

怎么修改Vue.js this的指向

這張圖說明了這 3 個函數是 Function prototype  的方法,也就是說「每個函數都有著三個方法」。當定義一個函數,這個函數默認包含這三個方法。

我們感受一下 Vue.js 中關于 apply、call 和 bind 的使用:

apply 的應用:

function once (fn) {   var called = false;   return function () {     if (!called) {       called = true;       fn.apply(this, arguments);     }   } }

call 的應用:

var hasOwnProperty = Object.prototype.hasOwnProperty; function hasOwn (obj, key) {   return hasOwnProperty.call(obj, key) }

bind的應用:

function polyfillBind (fn, ctx) {   function boundFn (a) {     var l = arguments.length;     return l       ? l > 1         ? fn.apply(ctx, arguments)         : fn.call(ctx, a)       : fn.call(ctx)   }    boundFn._length = fn.length;   return boundFn }  function nativeBind (fn, ctx) {   return fn.bind(ctx) }  var bind = Function.prototype.bind   ? nativeBind   : polyfillBind;

你可能看不懂上面的用法,下面我們一一拋開謎底。

當一個新事物的出現,總是有目的的,那么 apply、call 和 bind  的出現是為了解決什么問題呢?它們?yōu)槭裁词呛瘮档姆椒?為什么不是其它對象的方法。

通過 apply、call 可以自定義 this 調用某個函數,比如定義一個全局函數(嚴格模式):

'use strict'; function gFun(name, age) {     console.log(this); }

這個函數可以通過下面 5 種方式調用,也就是說通過 apply、call、bind 可以調用一個函數 F,其中「函數 F 執(zhí)行上下文中的 this  可以在調用時指定」:

1.直接調用:

gFun('suyan', 20); // this 為 undefined

2.通過 this 調用:

this.gFun('suyan', 20); // this 為 window

3.通過 apply 調用,把所有的參數組合成一個數組作為 apply 的參數:

gFun.apply(this, ['suyan', 20]); // this 為 window

4.通過 call 調用,參數通過逗號分割,這是與 apply 調用的區(qū)別:

gFun.call(this, 'suyan', 20);  // this 為 window

5.通過 bind 調用,會返回一個原函數的拷貝,并擁有指定的 this和參數:

let bGFun = gFun.bind(this, 'suyan', 20); bGFun();  // this 為 window

我們一起看一些例子:

例1、setTimeOut 的使用:

const time = {     second: 1,     afterOneSecond() {         setTimeout(function () {             this.second += 1;             console.log(this.second);         }, 1000);     } }; time.afterOneSecond();

上面這段代碼執(zhí)行后,第 6 行代碼的打印結果是 NaN,在連接你、我、他 —— this 這節(jié)課程中我們有提到過 this  設計的一個弊端是不能繼承。其實可以通過 bind 改造一下這個函數:

const time = {     second: 1,     afterOneSecond() {         setTimeout(this.timeInvoke.bind(this), 1000);     },     timeInvoke() {         this.second += 1;         console.log(this.second);     } }; time.afterOneSecond();

函數 timeInvoke 通過 bind 綁定 this,并返回一個新的函數,執(zhí)行結果為 2。bind 好像具有「暫存」的功能,把當前的 this  暫存起來。

例 2、函數調用

const person = {     name: 'suyan',     age: 20,     showName(pre) {         return pre + '-' + this.name;     },     update(name, age) {         this.name = name;         this.age = age;     } };  function generateName(fun) {     let name = fun();     console.log('showName = ', name); }  generateName(person.showName);

執(zhí)行上面代碼會報錯,因為 showName 中的 this 為 undefined:

怎么修改Vue.js this的指向

可以通過 bind 「暫存 this」:

const person = {     name: 'suyan',     age: 20,     showName(pre) {         return pre + '-' + this.name;     },     update(name, age) {         this.name = name;         this.age = age;     } };  function generateName(fun) {     let name = fun();     console.log('showName = ', name); } // 指定 this 為 person 對象 let bindShowName = person.showName.bind(person, '前端小課'); generateName(bindShowName);

例 3、構造函數,通過 call 來調用某個函數,替換 this。

function Product(name, price) {     this.name = name;     this.price = price; }  function Food(name, price) {     // 調用 Product 函數     Product.call(this, name, price);     this.catagory = 'food'; } let food = new Food('包子', 1); console.log(food.name); // 包子

例 4、調用匿名函數

const animals = [     {         name: 'King'     },     {         name: 'Fail'     } ];  for (let i = 0; i < animals.length; i++) {     (function (i) {         // 可以直接使用 this         this.print = function () {             console.log('#' + i + ' ' + this.name);         };         this.print();     }).call(animals[i], i); }

結果為:

怎么修改Vue.js this的指向

感謝各位的閱讀,以上就是“怎么修改Vue.js this的指向”的內容了,經過本文的學習后,相信大家對怎么修改Vue.js this的指向這一問題有了更深刻的體會,具體使用情況還需要大家實踐驗證。這里是億速云,小編將為大家推送更多相關知識點的文章,歡迎關注!

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI