Global execution
First, let’s see what this is in the global environment:
first. Browser:
console.log(this);
// Window {speechSynthesis: SpeechSynthesis, caches: CacheStorage, localStorage: Storage, sessionStorage: Storage, webkitStorageInfo: DeprecatedStorageInfo…}
You can see that the window object is printed;
second. node:
console.log(this);
// global
You can see that the global object is printed;
Summary: In the global scope, its this executes the current global object (Window on the browser side, global in node).
Execution in function
Pure function call
This is the most common way to use a function:
function test() { console.log(this); }; test(); // Window {speechSynthesis: SpeechSynthesis, caches: CacheStorage, localStorage: Storage, sessionStorage: Storage, webkitStorageInfo: DeprecatedStorageInfo…}
We can see that a function is When called directly, it is a global call, and its this points to the global object;
Strict mode 'use strict';
If a pure function call is executed in strict mode, Then this here will not point to the global world, but undefined. This approach is to eliminate some imprecise behaviors in js:
'use strict'; function test() { console.log(this); }; test(); // undefined
Of course, it would be better to put it in an immediate execution function , to avoid polluting the global situation:
(function (){ "use strict"; console.log(this); })(); // undefined
Called as a method of an object
When a function is called as a method of an object:
var obj = { name: 'qiutc', foo: function() { console.log(this.name); } } obj.foo(); // 'qiutc'
At this time, this points to The current object;
Of course, we can also do this:
function test() { console.log(this.name); } var obj = { name: 'qiutc', foo: test } obj.foo(); // 'qiutc'
The same remains unchanged, because everything in js is an object, and the function is also an object. For test, it is just a Function name, function reference, which points to this function. When foo = test, foo also points to this function.
What if you assign the object's method to a variable and then call the variable directly:
var obj = { name: 'qiutc', foo: function() { console.log(this); } } var test = obj.foo; test(); // Window
You can see that this executes the global at this time. When we put test = obj.foo, test directly points to a reference to a function. At this time, it actually has nothing to do with the object obj. Therefore, it is called directly as an ordinary function. Therefore, this points to the global object.
Some pitfalls
We often encounter some pitfalls in the callback function:
var obj = { name: 'qiutc', foo: function() { console.log(this); }, foo2: function() { console.log(this); setTimeout(this.foo, 1000); } } obj.foo2();
When we execute this code, we will find that this printed twice is different. :
The first time this is printed directly in foo2, which points to the object obj, we have no doubt;
But this.foo executed in setTimeout points to the global object, here Shouldn't you use it as a function method? This often confuses many beginners;
In fact, setTimeout is just a function, and the function must require parameters. We pass this.foo as a parameter to the setTimeout function, just like it requires a fun parameter. , when passing in parameters, we actually do the operation fun = this.foo. Did you see that? Here we directly point fun to the reference of this.foo; when executing, fun() is actually executed, so it has been combined with obj is irrelevant, it is called directly as an ordinary function, so this points to the global object.
This problem is commonly encountered in many asynchronous callback functions;
Solution
In order to solve this problem, we can use the characteristics of closures to deal with it:
var obj = { name: 'qiutc', foo: function() { console.log(this); }, foo2: function() { console.log(this); var _this = this; setTimeout(function() { console.log(this); // Window console.log(_this); // Object {name: "qiutc"} }, 1000); } } obj.foo2();
You can see that using this directly is still Window; because this in foo2 points to obj, we can first use a variable _this to store it, and then use _this in the callback function to point to the current one Object;
Another pitfall of setTimeout
As I said before, if the callback function is executed directly without a bound scope, then its this points to the global object (window ), will point to undefined in strict mode. However, the callback function in setTimeout behaves differently in strict mode:
'use strict'; function foo() { console.log(this); } setTimeout(foo, 1); // window
It stands to reason that we have added strict mode, and the foo call does not specify this, so it should be It comes out undefined, but the global object still appears here. Is the strict mode invalid?
No, even in strict mode, when the setTimeout method calls the incoming function, if the function does not specify this, then it will do an implicit operation - automatically inject the global context , equivalent to calling foo.apply(window) instead of foo();
Of course, if we have specified this when passing in the function, then the global object will not be injected, such as: setTimeout(foo .bind(obj), 1);;
http://stackoverflow.com/questions/21957030/why-is-window-still-defined-in-this-strict-mode-code
Used as a constructor
In js, in order to implement a class, we need to define some constructors. When calling a constructor, we need to add the new keyword:
function Person(name) { this.name = name; console.log(this); } var p = new Person('qiutc'); // Person {name: "qiutc"}
我们可以看到当作构造函数调用时,this 指向了这个构造函数调用时候实例化出来的对象;
当然,构造函数其实也是一个函数,如果我们把它当作一个普通函数执行,这个 this 仍然执行全局:
function Person(name) { this.name = name; console.log(this); } var p = Person('qiutc'); // Window
其区别在于,如何调用函数(new)。
箭头函数
在 ES6 的新规范中,加入了箭头函数,它和普通函数最不一样的一点就是 this 的指向了,还记得在上文中(作为对象的方法调用-一些坑-解决)我们使用闭包来解决 this 的指向问题吗,如果用上了箭头函数就可以更完美的解决了:
var obj = { name: 'qiutc', foo: function() { console.log(this); }, foo2: function() { console.log(this); setTimeout(() => { console.log(this); // Object {name: "qiutc"} }, 1000); } } obj.foo2();
可以看到,在 setTimeout 执行的函数中,本应该打印出在 Window,但是在这里 this 却指向了 obj,原因就在于,给 setTimeout 传入的函数(参数)是一个箭头函数:
函数体内的this对象,就是定义时所在的对象,而不是使用时所在的对象。
根据例子我们理解一下这句话:
在 obj.foo2() 执行的时候,当前的 this 指向 obj;在执行 setTimeout 时候,我们先是定义了一个匿名的箭头函数,关键点就在这,箭头函数内的 this 执行定义时所在的对象,就是指向定义这个箭头函数时作用域内的 this,也就是 obj.foo2 中的 this,即 obj;所以在执行箭头函数的时候,它的 this -> obj.foo2 中的 this -> obj;
简单来说, 箭头函数中的 this 只和定义它时候的作用域的 this 有关,而与在哪里以及如何调用它无关,同时它的 this 指向是不可改变的。
call, apply, bind
在 js 中,函数也是对象,同样也有一些方法,这里我们介绍三个方法,他们可以更改函数中的 this 指向:
call
fun.call(thisArg[, arg1[, arg2[, ...]]])
它会立即执行函数,第一个参数是指定执行函数中 this 的上下文,后面的参数是执行函数需要传入的参数;
apply
fun.apply(thisArg[, [arg1, arg2, ...]])
它会立即执行函数,第一个参数是指定执行函数中 this 的上下文,第二个参数是一个数组,是传给执行函数的参数(与 call 的区别);
bind
var foo = fun.bind(thisArg[, arg1[, arg2[, ...]]]);
它不会执行函数,而是返回一个新的函数,这个新的函数被指定了 this 的上下文,后面的参数是执行函数需要传入的参数;
这三个函数其实大同小异,总的目的就是去指定一个函数的上下文(this),我们以 call 函数为例;
为一个普通函数指定 this
var obj = { name: 'qiutc' }; function foo() { console.log(this); } foo.call(obj); // Object {name: "qiutc"}
可以看到,在执行 foo.call(obj) 的时候,函数内的 this 指向了 obj 这个对象,成功;
为对象中的方法指定一个 this
var obj = { name: 'qiutc', foo: function () { console.log(this); } } var obj2 = { name: 'tcqiu222222' }; obj.foo.call(obj2); // Object {name: "tcqiu222222"}
可以看到,执行函数的时候这里的 this 指向了 obj2,成功;
为构造函数指定 this
function Person(name) { this.name = name; console.log(this); } var obj = { name: 'qiutc2222222' }; var p = new Person.call(obj, 'qiutc'); // Uncaught TypeError: Person.call is not a constructor(…)
这里报了个错,原因是我们去 new 了 Person.call 函数,而非 Person ,这里的函数不是一个构造函数;
换成 bind 试试:
function Person(name) { this.name = name; console.log(this); } var obj = { name: 'qiutc2222222' }; var Person2 = Person.bind(obj); var p = new Person2('qiutc'); // Person {name: "qiutc"} console.log(obj); // Object {name: "qiutc2222222"}
打印出来的是 Person 实例化出来的对象,而和 obj 没有关系,而 obj 也没有发生变化,说明,我们给 Person 指定 this 上下文并没有生效;
因此可以得出: 使用 bind 给一个构造函数指定 this,在 new 这个构造函数的时候,bind 函数所指定的 this 并不会生效;
当然 bind 不仅可以指定 this ,还能传入参数,我们来试试这个操作:
function Person(name) { this.name = name; console.log(this); } var obj = { name: 'qiutc2222222' }; var Person2 = Person.bind(obj, 'qiutc111111'); var p = new Person2('qiutc'); // Person {name: "qiutc111111"}
可以看到,虽然指定 this 不起作用,但是传入参数还是起作用了;
为箭头函数指定 this
我们来定义一个全局下的箭头函数,因此这个箭头函数中的 this 必然会指向全局对象,如果用 call 方法改变 this 呢:
var afoo = (a) => { console.log(a); console.log(this); } afoo(1); // 1 // Window var obj = { name: 'qiutc' }; afoo.call(obj, 2); // 2 // Window
可以看到,这里的 call 指向 this 的操作并没有成功,所以可以得出: 箭头函数中的 this 在定义它的时候已经决定了(执行定义它的作用域中的 this),与如何调用以及在哪里调用它无关,包括 (call, apply, bind) 等操作都无法改变它的 this。
只要记住箭头函数大法好,不变的 this。
更多JavaScript 中的 this !相关文章请关注PHP中文网!