js this (simple)

js this

​this is a keyword in many programming languages. In JavaScript, this is generally understood in this way: the point of this cannot be determined when the function is defined. Only when the function is executed can it be determined who this points to. In fact, the final point of this is the object that called it

normal function call

Generally, if there is no specific reference, it points to the global object window

var username='cn'
function fn(){
    
    
    alert(this.username);//cn
}
fu();

window.username='cn'
function fn(){
    
    
    alert(this.username);//cn
}
fn();
//可以理解为
//window.fn();

Special case

let username='cn'
function fn(){
    
    
    alert(this.username);//undefined
}
fn();

Because the variable declared with let is not window

function call

function name direct call

 
 function myobj(){
    
    
     var myname = "发挥不广泛";
     console.log(this);
     console.log(this.myname);
 }
 myobj();//等价于 window.myobj();
//window
//undefined

Call by object function name

 var myname = "我是window的name";
 function myobj(){
    
    
     var myname = "发挥不广泛";
     console.log(this);
     console.log(this.myname);
 }
 var a = {
    
    
     fun:myobj, //将函数myobj 赋值给a.fun
     myname:"我是a的name"
 };
 myobj();
//window
//我是window的name
 a.fun();
//myname:我是a的name
//我是a的name


simple example

window.b=2222
let obj={
    
    
    a:111,
    fn:function(){
    
    
        alert(this.a);//111
        alert(this.b);//undefined
    }
}
obj.fn();
//this指向上下文

constructor call

let TestClass=function(){
    
    
    this.name='111';
}
let subClass=new TestClass();
subClass.name='cn';
console.log(subClass.name);//cn
let subClass1=new TestClass();
console.log(subClass1.name)//111

Guess you like

Origin blog.csdn.net/qq_51649346/article/details/124082536