聊聊js里面的this是代表什么?

239 阅读1分钟

聊聊js里面的this是代表什么?

定义:js是系统里预定义的一个变量,是个关键字。

一、全局this 指向了window(了解)

console.log(this);//Window

二、关注函数里的this : 注意:不需要关注函数的定义,需要关注函数的调用

//函数定义
function fn(){
      console.log("this是",this);
 }
// 1.直接调用 :this就指向window
fn(); //this 就指向window

2.通过事件触发调用函数 :this 就指向事件源(事件从哪里触发的)

 <button id="btn">按钮</button>
```js
function fn(){
      console.log("this是",this);
 }
 btn.onclick=fn;//点击按钮,控制台就会出现this是<button id="btn">按钮</button>

三、对象里的this 注意:不需要关注函数的定义 ,需要关注函数的调用

1.通过对象.函数(); this会指向调用的对象

var obj = {
            name:"小王",
            age:20,
            fn:function(){
                console.log(this);
            }
        }
obj.fn();//通过对象.函数()执行结果就是调用的对象  {name: "小王", age: 20, fn: ƒ}

2.直接通过函数调用

var obj = {
            name:"小王",
            age:20,
            fn:function(){
                console.log(this);
     }
 }
var myfn = obj.fn;  //函数没有执行
myfn();  //this 会指向window