修改 this 指向
生活随笔
收集整理的這篇文章主要介紹了
修改 this 指向
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
文章目錄
- 前言
- 一、new關鍵字改變this指向
- 二、 call()
- 三、apply()
- 四 、bind()
- 五、總結
前言
修改 this 指向,四種方法
一、new關鍵字改變this指向
//構造函數版this function Fn(){this.user = "追夢子"; } var a = new Fn(); console.log(a.user); //追夢子二、 call()
var a = {user:"追夢子",fn:function(){console.log(this.user); //追夢子} } var b = a.fn; b.call(a); //若不用call,則b()執行后this指的是Window對象call方法除了第一個參數以外還可以添加多個參數
var a = {user:"追夢子",fn:function(e,ee){console.log(this.user); //追夢子console.log(e+ee); //3} } var b = a.fn; b.call(a,1,2);三、apply()
var a = {user:"追夢子",fn:function(){console.log(this.user); //追夢子} } var b = a.fn; b.apply(a);apply方法和call方法有些相似,它也可以改變this的指向,也可以有多個參數,但是不同的是,第二個參數必須是一個數組
var a = {user:"追夢子",fn:function(e,ee){console.log(this.user); //追夢子console.log(e+ee); //11} } var b = a.fn; b.apply(a,[10,1]);//注意如果call和apply的第一個參數寫的是null,那么this指向的是window對象
var a = {user:"追夢子",fn:function(){console.log(this); //Window {external: Object, chrome: Object, document: document, a: Object, speechSynthesis: SpeechSynthesis…}} } var b = a.fn; b.apply(null);四 、bind()
var a = {user:"追夢子",fn:function(){console.log(this.user);} } var b = a.fn; b.bind(a); //代碼沒有被打印我們發現代碼沒有被打印,對,這就是bind和call、apply方法的不同,實際上bind方法返回的是一個修改過后的函數
var a = {user:"追夢子",fn:function(){console.log(this.user); //追夢子} } var b = a.fn; var c = b.bind(a); c();五、總結
區別:
call和apply都是改變上下文中的this并立即執行這個函數
bind方法可以讓對應的函數想什么時候調就什么時候調用,并且可以將參數在執行的時候添加,這是它們的區別
call()、bind()、apply()的用法,改變this的指向,區別在于
f.call(obj, arg1, arg2…),
f.bind(obj, arg1, arg2,…)(),
f.apply(obj, [arg1, arg2, .])
總結
以上是生活随笔為你收集整理的修改 this 指向的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: uni-app动态绑定class和sty
- 下一篇: uniapp uni.request G