1 ES6 point in this is to find the nearest point to this outer layer.
When this point is not changed, an arrow in this function, there are two cases
- 1 this point to the element to be registered
<script>
var btn=document.querySelector(button);
btn.onclick=function(){
console.log(this);//this 指向btn
}
</script>
- 2this point window, in a subject, a subject array, the function, the function of the arrows point to this window. In this case the outermost layer is a global function
// 1 对象中的箭头函数的this指向window
var obj = {
name: 'lxf',
say: () => {
console.log(this);
console.log('对象中箭头函数中的this' + this);
}
}
obj.say();
// 2 函数中的箭头函数中的this指向window
function fun() {
let a = () => {
console.log('函数中 箭头函数中的this:' + this);
}
a(); //调用箭头函数
}
fun();
// 3 数组对象中的 箭头函数中的this指向window
var arr1 = [{
name: 'age',
say: () => {
console.log('函数中的箭头函数中的this'+this);
}
}]
arr1[0].say();
2 does not change this point, the conventional function of this point there are two cases
- Pointing instance of an object
// 创建对象时this的指向
function Start(a, b, c) {
this.uname = a;
this.age = b;
this.sex = c;
this.say = function() {
console.log(this); //此时的this指向实例对象,
}
}
var ldh = new Start('ldh', 18, 'man');
ldh.say(); //在此this指向ldh这个对象
- Pointing to the caller
var obj = {
uname: 'deng',
age: 18,
sex: 'man',
say: function() {
console.log(this);
}
}
obj.say(); //this指向obj,是obj调用的。
<script>
var btn=document.querySelector(button);
btn.onclick=function(){
console.log(this);//this 指向btn
}
</script>