On this point in JavaScript
1. Default point, this point is the default window object
console.log(this);//打印的是window
2. When the function call
2.1 Independent calls, this points to the window object
function test(){
console.log(this);//打印的是window
}
window.test();//简写test()
2.2 function as a method of an object, this points to the current object
let obj = {
name:"test",
show:function(){
console.log(this);//这个打印出来的是window
}
}
let a = obj.show;//a就是function(){console.log(this);}
a();//window.a();
3. Point to the current object
let obj = {
name:'test',
age:19,
show:function(){
console.log(this);
}
}
obj.show();//打印出来的是Object
Elements 4.this point binding, when the function as an event handler, then this is the binding element points
<body>
<button>点击</button>
</body>
<script>
document.querySelector("button").onclick=function(){
console.log(this);
}
</script>
The change of this point
5.1 call()
let obj={
name:'hello',
age:19,
show:function(x,y){
console.log(this);//Object
console.log(this.name);//张三
console.log(this.age+x+y);//50
}
}
let obj2={
name:'张三',
age:30
}
obj.show.call(obj2,10,10);
5.2 aplly()
let obj={
name:'hello',
age:19,
show:function(x,y){
console.log(this);//Object
console.log(this.name);//张三
console.log(this.age+x+y);//60
}
}
let obj2={
name:'张三',
age:30
}
obj.show.apply(obj2,[10,20]);
es5 the bind ()
let obj={
name:'hello',
age:19,
show:function(x,y){
console.log(this);//Object
console.log(this.name);//张三
console.log(this.age+x+y);//60
}
}
let obj2={
name:'张三',
age:30
}
let test = obj.show.bind(obj2);
test(10,20);
6. The arrows point to this function, it always points to this refers to the enclosing scope
Since this binding is not a function of the arrow, it captures it at this value (i.e., a position defined) context, this value as its
let obj = {
name:"test",
show:()=>{
console.log(this);//打印出Window
}
}
obj.show();