在HTML中使用vue
在下面的代码中,这里的this指向对象vm,因而可以使用创建的Vue对象中的data内的数据及methods方法。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script type="text/javascript" src = "https://cdn.bootcdn.net/ajax/libs/vue/2.6.14/vue.min.js"></script>
</head>
<body>
<script>
const vm = new Vue({
data(){
return {
msg: 'This 的指向'
}
},
methods: {
testFn(){
console.log('msg',this.msg)
}
}
})
vm.testFn();
</script>
</body>
</html>
JavaScript中使用this
目前我所了解到的可总结为四种情况:
1、 当函数作为一个函数(function)被调用时,分为两种情况
- 此时不是作为对象的属性
- 在非严格模式下,this就指向window对象(即全局对象)
function show(){
console.log('show:this',this);
}
show();
- 在严格模式下,this指向undefined
function strictShow(){
'use strict'; //使用严格模式
console.log('strictShow:this',this);
}
strictShow();
2、作为方法(method)被调用
*-*方法:当函数作为一个对象的属性时,称这个函数为方法,当通过方法被调用时,this指向的是方法的拥有者。(尤其注意箭头函数的使用)
let obj = {
idol: '鞠婧祎',
promoter: 'goulizi',
show1(){
console.log('show_this_fir', this);
},
show2: function(){
console.log('show_this_sec', this);
},
show3: () => {
console.log('show_this_tir', this);
},
};
obj.show1();
obj.show2();
obj.show3();
*-*可以看出前两次都是指向obj对象,而第三次则指向Window,原因如下:第三次使用了 ‘=>’ 箭头函数,而箭头函数本身是没有this的,它的this是继承于它父级的this,这里它的父级就是obj对象,而obj对象的this,所指向的就是Window 。
3、作为构造函数来使用(即使用 new 时)
*-*构造函数与普通函数的区别:构造函数的首字母大写
- 正常情况下的构造函数
function Gou(){
this.idol = '鞠婧祎';
this.promoter = 'goulizi';
}
let Gai = new Gou();
console.log('Gai: ', Gai);
*-*new的过程中所发生的事情:创建一个空对象 --》 该空对象作为this参数传递给构造函数,从而成为构造函数的上下文 --》 新构造的对象作为 new 运算符的返回值返回(有例外情况,见下文)
- 若构造函数本身便具有返回值
function Gou(){
this.idol = '鞠婧祎';
this.promoter = 'goulizi';
return 1;
}
let Gai = new Gou();
console.log('Gai: ', Gai);
*-*仍无变化
- 当构造函数本身便返回一个对象
*-*则在控制台现实的便是那个返回的对象(重点注意)
function Gou(){
this.idol = '鞠婧祎';
this.promoter = 'goulizi';
return {
name: '小鞠',
};
}
let Gai = new Gou();
console.log('Gai: ', Gai);
4、通过call和apply显示修改this ( 个人感觉是在1[作为function被调用]的基础上进行变化 )
- call 在修改 this 时如果需要传参,要一个一个传递
let goulizi = {
idol: '鞠婧祎',
promoter: 'goushiliu',
};
function show(...args){
console.log(this, args);
}
show(1,2,3);
show.call(goulizi,1,2,3);
*-*可以看到,若是直接使用show方法,便会变成第一种(即作为function被调用),此时 this 的指向便是Window;而若在show方法后面使用call方法,则会将 goulizi 作为 this 的指向,从而输出该对象内的内容
- apply 在修改 this 时,可将数据化为一组进行传递
let goulizi = {
idol: '鞠婧祎',
promoter: 'goushiliu',
};
function show(...args){
console.log(this, args);
}
show(1,2,3);
show.apply(goulizi,[1,2,3]);
若不进行传参,则call与apply几乎无区别。