1.this
this不是在定义的时候确定的,而是在调用的时候确定的
this的情况:
1.当以函数的形式调用时 this 是 window;
2.当以方法的形式调用时,谁调用方法 this 就是谁;
3.当以构造函数的形式调用时, this 就是新创建的那个对象;
<div id="box"></div>
<script>
var box = document.getElementById('box');
function fn() {
console.log(this);
}
// 函数中的this不是定义的时候确定的,而是调用的时候确定的,调用的方式不同,this的指向不同
1、普通函数中的this
// 1、事件触发的函数,函数中的this是触发这个函数的元素
box.onclick = fn;
2、事件函数中的this
// 2、函数名() 调用,函数中的this就是window
fn(); // window
// 1,2合用
box.onclick = function () {
console.log(this); // box
fn(); // window
}
3、对象方法中的this
// 3、做为对象的方法调用
var obj = {
name: 'zs',
ab: function () {
console.log(this);
}
}
console.log(obj.name);
// 做为对象的方法调用,函数中的this就是这个对象
obj.ab(); // obj
</script>