there is no relationship between this point in the function and where the current function is defined or executed.
The following rules are analyzed for this point:
[non-strict mode]
1. This is always the window in the self-executing function
[Case 1]
var obj={
fn: (function (i) {
//this->window
return function () {
//this->obj
}
}) (0)
};
Obj.fn ();
2. Bind a method to an element's behavior, and when the behavior is triggered, the method of binding is executed, and this is the current element in the method .
[Case 1]
odiv.onclick=function () {
//this->odiv
};
[Case 2]
function fn () {
//this->window
}
odiv.onclick=function () {
//this->odiv
fn ();
};
3, method execution, look at the method name before the ".", if there is, "." Who's in front, this is who, no, this is window.
[Case 1]
var obj={fn:fn};
function fn () {}
fn.prototype.aa=function () {};
var f=new fn;
fn ();//this->window
Obj.fn ();//this->obj
Fn.prototype.aa ();//this->fn.prototype
F.aa ();//this->f
F.__proto__.aa ();//this->f.__proto__->fn.prototype
4, in the constructor mode, the this.xxx=xxx in the function body is an instance of the current class
[Case 1]
function Fn () {
this.x=100;//this->f
this.getx=function () {
Console.log (this);//this->f because the Getx method executes, "." The front is F, so this is the F
}
}
var f=new Fn;
f.getx ();
5, the use of call/apply to change the direction of this (but encountered call/apply the above four are useless)
[Strict mode]
the "use strict";//-> tells the browser that the JS code we're writing next uses strict mode
1. This in self-executing function is always undefined
[Case 1]
var obj={
fn: (function (i) {
//this->undefined
return function () {
//this->obj
}
}) (0)
};
Obj.fn ();
3, method execution, look at the method name before the ".", if there is, "." Who's in front of this is who, if not, this is undefined.
[Case 1]
var obj={fn:fn};
function fn () {}
fn ();//this->undefined
Obj.fn ();//this->obj
we find that this is the main difference between this and the non-strict mode in strict mode: In the case that there is no write execution body in the JS code, the default is window execution in the non-strict mode, so this point is the window, but in strict mode, No writing is no Executive body, this point is undefined;
The this point problem in JS