<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<script src="http://libs.baidu.com/jquery/2.0.0/jquery.js"></script>
<script src="https://unpkg.com/vue@2.5.9/dist/vue.js"></script>
</head>
<div id="app" style="width: 100%;height: auto;font-size:20px;">
<p id="id1"></p>
<p id="id2"></p>
</div>
<script type="text/javascript">
var message = "Hello!";
var app = new Vue({
el:"#app",
data:{
message: "你好!"
},
created: function() {
this.showMessage1(); //this 1
this.showMessage2(); //this 2
},
methods:{
showMessage1:function(){
setTimeout(function() {
document.getElementById("id1").innerText = this.message; //this 3
}, 10)
},
showMessage2:function() {
setTimeout(() => {
document.getElementById("id2").innerText = this.message; //this 4
}, 10)
}
}
});
</script>
</html>
第一個輸出英文"Hello!”,第二個輸出中文“你好!”。這說明了showMessage1()里的this指的是window,而showMessage2()里的this指的是vue實例。
※ 對於普通函數(包括匿名函數),this指的是直接的調用者,在非嚴格模式下,如果沒有直接調用者,this指的是window。showMessage1()里setTimeout使用了匿名函數,this指向
window。
※ 箭頭函數是沒有自己的this,在它內部使用的this是由它定義的宿主對象決定。showMessage2()里定義的箭頭函數宿主對象為vue實例,所以它里面使用的this指向vue實例。