前言
JS 中 this 指向问题是个老生常谈的问题了, 下面这篇文章再来给大家介绍下, 大家可以看看, 更深入的了解了解, 下面话不多说了, 来一起看看详细的介绍吧
this
this: 上下文, 会根据执行环境变化而发生指向的改变.
1. 单独的 this, 指向的是 Windows 这个对象
alert(this); // this -> Windows
2. 全局函数中的 this
- function demo() {
- alert(this); // this -> Windows
- }
- demo();
在严格模式下, this 是 undefined.
- function demo() {
- 'use strict';
- alert(this); // undefined
- }
- demo();
3. 函数调用的时候, 前面加上 new 关键字
所谓构造函数, 就是通过这个函数生成一个新对象, 这时, this 就指向这个对象.
- function demo() {
- //alert(this); // this -> object
- this.testStr = 'this is a test';
- }
- let a = new demo();
- alert(a.testStr); // 'this is a test'
前端全栈学习交流圈: 866109386, 面向 1-3 经验年前端开发人员, 帮助突破技术瓶颈, 提升思维能力, 群内有大量 PDF 可供自取, 更有干货实战项目视频进群免费领取.
4. 用 call 与 apply 的方式调用函数
- function demo() {
- alert(this);
- }
- demo.call('abc'); // abc
- demo.call(null); // this -> Windows
- demo.call(undefined); // this -> Windows
5. 定时器中的 this, 指向的是 Windows
- setTimeout(function() {
- alert(this); // this -> Windows , 严格模式 也是指向 Windows
- },500)
6. 元素绑定事件, 事件触发后, 执行的函数中的 this, 指向的是当前元素
- Windows.onload = function() {
- let $btn = document.getElementById('btn');
- $btn.onclick = function(){
- alert(this); // this -> 当前触发
- }
- }
前端全栈学习交流圈: 866109386, 面向 1-3 经验年前端开发人员, 帮助突破技术瓶颈, 提升思维能力, 群内有大量 PDF 可供自取, 更有干货实战项目视频进群免费领取.
7. 函数调用时如果绑定了 bind, 那么函数中的 this 指向了 bind 中绑定的元素
- Windows.onload = function() {
- let $btn = document.getElementById('btn');
- $btn.addEventListener('click',function() {
- alert(this); // Windows
- }.bind(Windows))
- }
8. 对象中的方法, 该方法被哪个对象调用了, 那么方法中的 this 就指向该对象
- let name = 'finget'
- let obj = {
- name: 'FinGet',
- getName: function() {
- alert(this.name);
- }
- }
- obj.getName(); // FinGet
--------------------------- 分割线 ----------------------------
- let fn = obj.getName;
- fn(); //finget this -> Windows
腾讯笔试题
- var x = 20;
- var a = {
- x: 15,
- fn: function() {
- var x = 30;
- return function() {
- return this.x
- }
- }
- }
- console.log(a.fn());
- console.log((a.fn())());
- console.log(a.fn()());
- console.log(a.fn()() == (a.fn())());
- console.log(a.fn().call(this));
- console.log(a.fn().call(a));
前端全栈学习交流圈: 866109386, 面向 1-3 经验年前端开发人员, 帮助突破技术瓶颈, 提升思维能力, 群内有大量 PDF 可供自取, 更有干货实战项目视频进群免费领取.
答案
1.console.log(a.fn());
对象调用方法, 返回了一个方法.
- function() {
- return this.x
- }
- 2.console.log((a.fn())());
a.fn() 返回的是一个函数,()() 这是自执行表达式. this -> Windows
- 20
- 3.console.log(a.fn()());
a.fn() 相当于在全局定义了一个函数, 然后再自己调用执行. this -> Windows
- 20
- 4.console.log(a.fn()() == (a.fn())());
- true
- 5.console.log(a.fn().call(this));
这段代码在全局环境中执行, this -> Windows
- 20
- 6.console.log(a.fn().call(a));
- this -> a
- 15
来源: http://www.jianshu.com/p/8fd3396dc18e