this指向
- 1、直接调用,指向全局
- 2、全局函数中的this
- 3、构造函数普通调用,指向全局(构造函数也是普通函数,可以正常执行)
- 4、构造函数通过new调用创建一个实例对象,指向这个实例对象
- 5、对象(json创建)里面的方法调用,指向这个对象
- 6、对象(通过Object创建)里面的方法调用,指向这个对象
- 7、对象(通构造函数创建)里面的方法调用,指向这个对象
- 8、函数调用的时候,前面加上 new 关键字
- 9、用call 与 apply 的方式调用函数
- 10、定时器中的this,指向的是window
- 11、元素绑定事件,事件触发后,执行的函数中的this,指向的是当前元素
- 12、函数调用时如果绑定了bind,那么函数中的this指向了bind中绑定的元素
- 13、对象中的方法,该方法被哪个对象调用了,那么方法中的 this 就指向该对象
1、直接调用,指向全局
console.log(this); // window

2、全局函数中的this
- 在普通函数里调用,指向全局
function fn(){
console.log(this);
}
fn();

- 在严格模式下,this 是undefined
function demo(){
'use strict';
console.log(this); // undefined
}
demo();

3、构造函数普通调用,指向全局(构造函数也是普通函数,可以正常执行)
function Car(){
this.name="奥迪";
console.log(this);
}
Car();

4、构造函数通过new调用创建一个实例对象,指向这个实例对象
var x = 0;
function Student(name,x){
this.name=name;
this.x=x;
console.log(this.x)
}
var zhangsna=new Student("zhangsan",1);
var lisi=new Student("lisi",2);

5、对象(json创建)里面的方法调用,指向这个对象
var object1={
name:"zhangsan",
show:function(){
console.log(this);
}
}
object1.show();

6、对象(通过Object创建)里面的方法调用,指向这个对象
var object2 = new Object();
object2.name='zhangsan';
object2.show=function(){
console.log(this);
}
object2.show();

7、对象(通构造函数创建)里面的方法调用,指向这个对象
function Student(){
this.name="zhangsan"
this.show=function(){
console.log(this);
}
}
var object3 = new Student();
object3.show();

8、函数调用的时候,前面加上 new 关键字
所谓构造函数,就是通过这个函数生成一个新对象,这时,this就指向这个对象
function demo(){
//alert(this); //this ->object
this.testStr='this is a test';
}
let a = new demo();
console.log(a.testStr); // 'this is a test'

9、用call 与 apply 的方式调用函数
function demo(){
console.log(this);
}
demo.call('abc'); // abc
demo.call(null); // this -> window
demo.call(undefined); // this -> window

10、定时器中的this,指向的是window
setTimeout(function(){
console.log(this); // this -> window , 严格模式也是指向window
},500)

11、元素绑定事件,事件触发后,执行的函数中的this,指向的是当前元素
window.onload = function(){
let $btn = document.getElemnetById('btn');
$btn.onclick = function(){
console.log(this); // this -> 当前触发
}
}

12、函数调用时如果绑定了bind,那么函数中的this指向了bind中绑定的元素
window.onload = function(){
let $btn = document.getElementById('btn');
$btn.addEventListener('click',function(){
console.log(this); // window
}.bind(window))
}

13、对象中的方法,该方法被哪个对象调用了,那么方法中的 this 就指向该对象
let name = '奥迪'
let obj = {
name:'迪迦',
getName:function(){
console.log(this.name);
}
}
obj.getName(); // 迪迦
------分隔-------
let fn = obj.getName;
fn(); // 奥迪 this -> window

本文详细探讨了JavaScript中this的指向,包括直接调用、全局函数、构造函数、对象方法、new关键字、call和apply方法、定时器、事件绑定等多种情况下的this指向,帮助理解JavaScript中的上下文环境。
490

被折叠的 条评论
为什么被折叠?



