欢迎光临散文网 会员登陆 & 注册

千锋教育JavaScript全套视频教程(10天学会Js,前端javascrip

2023-07-12 19:11 作者:神灬宝丶  | 我要投稿

P118 this指向

JavaScript中的this关键字是一个非常重要的概念,它在不同的情况下指向不同的对象。

this关键字的指向可以根据函数的调用方式而变化。

在全局作用域下,this指向window

在私有作用域下有以下几种情况

1.普通函数:this指向window

function myFunction() {

 console.log(this); // 输出 window

}

myFunction();

2.定时器中的函数:this指向window

function fun() { console.log(this);   }

setTimeout(fun,1000) // 输出 window

3.对象中的函数:this指向前面的对象

const myObj = {

name: 'John',

greet() {

console.log(`Hello, my name is ${this.name}`);

}

};

myObj.greet(); // 输出 "Hello, my name is John"

4.事件处理函数:this指向事件源

btn.onclick =function() {

      console.log(this);   //指向btn

}

5.自执行函数:this指向window

 function fun() {console.log(this);   // 输出 window}

(fun)()

6.构造函数:this指向实例

function Person(name) {

this.name = name;

}

const john = new Person('John');

console.log(john.name); // 输出 "John"

7.原型对象:this指向实例

8.箭头函数:this指向定义函数时的上下文

const myObj = {

name: 'John',

greet: () => {

console.log(`Hello, my name is ${this.name}`);

}

};

myObj.greet(); // 输出 "Hello, my name is undefined"

千锋教育JavaScript全套视频教程(10天学会Js,前端javascrip的评论 (共 条)

分享到微博请遵守国家法律