Vue的this
一、vue編譯模塊
(1)模塊域中導出對象域
export default {data() {return {msg: ''};} };A.function定義函數
I、模塊導出對象的各關鍵字的屬性值
如data的值
export default {props:['propA'},data:function() {//經Vue轉換,該函數屬于Vue的data賦值函數let c= this.propA; return {c:c,msg: this.propA, //經Vue轉換,msg屬于Vue實例的屬性func:function(){ //經Vue轉換,該函數屬于Vue實例的函數return this.propA;}};} };此處的this都是Vue的實例
?
II、模塊導出對象的屬性的子屬性
export default {props:['propA'},data:function() {return {msg:{ //經Vue轉換,msg屬于Vue實例的屬性propA:'zzzz',func:function(){return this.propA; //func是msg的成員方法}}};} };此處的this都是return的對象
?
III、函數中定義函數
export default {props:['propA'},data:function() {return {msg:{ //經Vue轉換,msg屬于Vue實例的屬性propA:'zzzz',func:function(){;(function(){alert(this.propA) //匿名函數})();}}};} };此處的this為undefined;由于匿名函數不屬于定義對象所有,又在編譯的模塊中,造成window對象被屏蔽,故為undefined
?
B.lamda表達式
export default {props:['propA'},data:()=>{ //經Vue轉換,該函數屬于Vue的data賦值函數let c= this.propA; //(1)return {c:c,msg: this.propA, //(2)func:function(){ return this.propA;//(3)},func1:()=>{ return this.propA;//(4)},other:{propA:'xzxz',func2:function(){ return this.propA;//(5)},func3:()=>{ return this.propA;//(6)}};};} };(1)、(2)、(4)、(6)經webpack編譯,將this轉換為_this(此名有沖突會變化),而_this正為webpack模塊的導出對象__webpack_exports__
(3)經Vue轉換,該函數屬于Vue實例的函數,故this指向Vue的實例
(5)中function定義沒有改變this,this指向other的對象
lamda表達式函數作用域的this都是當前聲明函數作用域的this
?
(2)模塊域中非導出對象域
<script> export default {data() {return {msg: ''};} }; //模塊域非導出對象的域 </script>A、沒有聲明作用域
<script> export default {};let b = function () {var ccc=b;var u = [this];try {this.a = 2;} catch (e) {u.push(e);}let c = function () {var u = [this];try {this.a = 3;} catch (e) {u.push(e);}let d = function () {var u = [this];try {this.a = 4;} catch (e) {u.push(e);}return u}return [u, d()]}return [u].concat(c()); } //(3) </script>I、(3)處插入let c=b();,結果調用的this全是undefined
II、(3)處插入let c=window.b();,結果window.b為undefined
?
B、有聲明作用域
<script> export default {};window.b = function () {var ccc=b;var u = [this];try {this.a = 2;} catch (e) {u.push(e);}let c = function () {var u = [this];try {this.a = 3;} catch (e) {u.push(e);}let d = function () {var u = [this];try {this.a = 4;} catch (e) {u.push(e);}return u}return [u, d()]}return [u].concat(c()); } //(3) </script>I、(3)處插入let c=b();,調用結果的this全是undefined
II、(3)處插入let c=window.b();,調用結果的this,第一個為window,其他的是undefined
?
二、Vue非編譯模塊
與vue編譯模塊類似,不同的是:
(1)function定義函數
vue編譯模塊的this的值為undefined,在vue非編譯模塊中全為window
(2)lamda表達式
lamda表達式中的this為父級的this,其中頂級的this為window
define(function () {var template =`<div>aaa</div>`;let component = {template: template,data:()=>{let that=this;//windowreturn {};}};return component; });?
?
?
?
?
?
總結
- 上一篇: WP Engine vs GoDaddy
- 下一篇: vue-router 如何在当前路由下重