JavaScript中this关键词的使用技巧、工作原理以及注意事项


Posted in Javascript onMay 20, 2014

要根据this 所在的位置来理解它,情况大概可以分为3种:

1、在函数中:this 通常是一个隐含的参数。

2、在函数外(顶级作用域中):在浏览器中this 指的是全局对象;在Node.js中指的是模块(module)的导出(exports)。

3、传递到eval()中的字符串:如果eval()是被直接调用的,this 指的是当前对象;如果eval()是被间接调用的,this 就是指全局对象。

对这几个分类,我们做了相应的测试:

1、在函数中的this

函数基本可以代表JS中所有可被调用的结构,所以这是也最常见的使用this 的场景,而函数又能被子分为下列三种角色:

    实函数
    构造器
    方法

1.1  在实函数中的this

在实函数中,this 的值是取决于它所处的上下文的模式。

Sloppy模式:this 指的是全局对象(在浏览器中就是window)。

function sloppyFunc() {
    console.log(this === window); // true
}
sloppyFunc();

Strict模式:this 的值是undefined。

function strictFunc() {
    'use strict';
    console.log(this === undefined); // true
}
strictFunc();

this 是函数的隐含参数,所以它的值总是相同的。不过你是可以通过使用call()或者apply()的方法显示地定义好this的值的。

function func(arg1, arg2) {
    console.log(this); // 1
    console.log(arg1); // 2
    console.log(arg2); // 3
}
func.call(1, 2, 3); // (this, arg1, arg2)
func.apply(1, [2, 3]); // (this, arrayWithArgs)

1.2  构造器中的this

你可以通过new 将一个函数当做一个构造器来使用。new 操作创建了一个新的对象,并将这个对象通过this 传入构造器中。

var savedThis;
function Constr() {
    savedThis = this;
}
var inst = new Constr();
console.log(savedThis === inst); // true

JS中new 操作的实现原理大概如下面的代码所示(更准确的实现请看这里,这个实现也比较复杂一些):

function newOperator(Constr, arrayWithArgs) {
    var thisValue = Object.create(Constr.prototype);
    Constr.apply(thisValue, arrayWithArgs);
    return thisValue;
}

1.3  方法中的this

在方法中this 的用法更倾向于传统的面向对象语言:this 指向的接收方,也就是包含有这个方法的对象。

var obj = {
    method: function () {
        console.log(this === obj); // true
    }
}
obj.method();

2、作用域中的this

在浏览器中,作用域就是全局作用域,this 指的就是这个全局对象(就像window):

<script>
    console.log(this === window); // true
</script>

在Node.js中,你通常都是在module中执行函数的。因此,顶级作用域是个很特别的模块作用域(module scope):

// `global` (not `window`) refers to global object:
console.log(Math === global.Math); // true// `this` doesn't refer to the global object:
console.log(this !== global); // true
// `this` refers to a module's exports:
console.log(this === module.exports); // true

3、eval()中的this

eval()可以被直接(通过调用这个函数名'eval')或者间接(通过别的方式调用,比如call())地调用。要了解更多细节,请看这里。

// Real functions
function sloppyFunc() {
    console.log(eval('this') === window); // true
}
sloppyFunc();function strictFunc() {
    'use strict';
    console.log(eval('this') === undefined); // true
}
strictFunc();
// Constructors
var savedThis;
function Constr() {
    savedThis = eval('this');
}
var inst = new Constr();
console.log(savedThis === inst); // true
// Methods
var obj = {
    method: function () {
        console.log(eval('this') === obj); // true
    }
}
obj.method();

 4、与this有关的陷阱

你要小心下面将介绍的3个和this 有关的陷阱。要注意,在下面的例子中,使用Strict模式(strict mode)都能提高代码的安全性。由于在实函数中,this 的值是undefined,当出现问题的时候,你会得到警告。

4.1  忘记使用new

如果你不是使用new来调用构造器,那其实你就是在使用一个实函数。因此this就不会是你预期的值。在Sloppy模式中,this 指向的就是window 而你将会创建全局变量:

function Point(x, y) {
    this.x = x;
    this.y = y;
}
var p = Point(7, 5); // we forgot new!
console.log(p === undefined); // true// Global variables have been created:
console.log(x); // 7
console.log(y); // 5

不过如果使用的是strict模式,那你还是会得到警告(this===undefined):

function Point(x, y) {
    'use strict';
    this.x = x;
    this.y = y;
}
var p = Point(7, 5);
// TypeError: Cannot set property 'x' of undefined

4.2 不恰当地使用方法

如果你直接取得一个方法的值(不是调用它),你就是把这个方法当做函数在用。当你要将一个方法当做一个参数传入一个函数或者一个调用方法中,你很可能会这么做。setTimeout()和注册事件句柄(event handlers)就是这种情况。我将会使用callIt()方法来模拟这个场景:

/** Similar to setTimeout() and setImmediate() */
function callIt(func) {
    func();
}

如果你是在Sloppy模式下将一个方法当做函数来调用,*this*指向的就是全局对象,所以之后创建的都会是全局的变量。

var counter = {
    count: 0,
    // Sloppy-mode method
    inc: function () {
        this.count++;
    }
}
callIt(counter.inc);// Didn't work:
console.log(counter.count); // 0
// Instead, a global variable has been created
// (NaN is result of applying ++ to undefined):
console.log(count);  // NaN

如果你是在Strict模式下这么做的话,this是undefined的,你还是得不到想要的结果,不过至少你会得到一句警告:

var counter = {
    count: 0,
    // Strict-mode method
    inc: function () {
        'use strict';
        this.count++;
    }
}
callIt(counter.inc);// TypeError: Cannot read property 'count' of undefined
console.log(counter.count);

要想得到预期的结果,可以使用bind():

var counter = {
    count: 0,
    inc: function () {
        this.count++;
    }
}
callIt(counter.inc.bind(counter));
// It worked!
console.log(counter.count); // 1

bind()又创建了一个总是能将this的值设置为counter 的函数。

4.3 隐藏this

当你在方法中使用函数的时候,常常会忽略了函数是有自己的this 的。这个this 又有别于方法,因此你不能把这两个this 混在一起使用。具体的请看下面这段代码:

var obj = {
    name: 'Jane',
    friends: [ 'Tarzan', 'Cheeta' ],
    loop: function () {
        'use strict';
        this.friends.forEach(
            function (friend) {
                console.log(this.name+' knows '+friend);
            }
        );
    }
};
obj.loop();
// TypeError: Cannot read property 'name' of undefined

上面的例子里函数中的this.name 不能使用,因为函数的this 的值是undefined,这和方法loop()中的this 不一样。下面提供了三种思路来解决这个问题:

1、that=this,将this 赋值到一个变量上,这样就把this 显性地表现出来了(除了that,self 也是个很常见的用于存放this的变量名),之后就使用那个变量:

loop: function () {
    'use strict';
    var that = this;
    this.friends.forEach(function (friend) {
        console.log(that.name+' knows '+friend);
    });
}

2、bind()。使用bind()来创建一个函数,这个函数的this 总是存有你想要传递的值(下面这个例子中,方法的this):

loop: function () {
    'use strict';
    this.friends.forEach(function (friend) {
        console.log(this.name+' knows '+friend);
    }.bind(this));
}

3、用forEach的第二个参数。forEach的第二个参数会被传入回调函数中,作为回调函数的this 来使用。

loop: function () {
    'use strict';
    this.friends.forEach(function (friend) {
        console.log(this.name+' knows '+friend);
    }, this);
}

5、最佳实践

理论上,我认为实函数并没有属于自己的this,而上述的解决方案也是按照这个思想的。ECMAScript 6是用箭头函数(arrow function)来实现这个效果的,箭头函数就是没有自己的this 的函数。在这样的函数中你可以随便使用this,也不用担心有没有隐式的存在。

loop: function () {
    'use strict';
    // The parameter of forEach() is an arrow function
    this.friends.forEach(friend => {
        // `this` is loop's `this`
        console.log(this.name+' knows '+friend);
    });
}

我不喜欢有些API把this 当做实函数的一个附加参数:

beforeEach(function () {  
    this.addMatchers({  
        toBeInRange: function (start, end) {  
            ...
        }  
    });  
});

把一个隐性参数写成显性地样子传入,代码会显得更好理解,而且这样和箭头函数的要求也很一致:

beforeEach(api => {
    api.addMatchers({
        toBeInRange(start, end) {
            ...
        }
    });
});
Javascript 相关文章推荐
Sample script that deletes a SQL Server database
Jun 16 Javascript
javascript 全角转换实现代码
Jul 17 Javascript
jQeury淡入淡出需要注意的问题
Sep 08 Javascript
查找Oracle高消耗语句的方法
Mar 22 Javascript
setInterval计时器不准的问题解决方法
May 08 Javascript
JavaScript中setTimeout的那些事儿
Nov 14 Javascript
bootstrap中模态框、模态框的属性实例详解
Feb 17 Javascript
从零开始实现Vue简单的Toast插件
Dec 03 Javascript
JavaScript设计模式--桥梁模式引入操作实例分析
May 23 Javascript
js编写简易的计算器
Jul 29 Javascript
5种方法告诉你如何使JavaScript 代码库更干净
Sep 15 Javascript
vue实现滑动解锁功能
Mar 03 Vue.js
Jquery插件分享之气泡形提示控件grumble.js
May 20 #Javascript
实现网页页面跳转的几种方法(meta标签、js实现、php实现)
May 20 #Javascript
jQuery.holdReady()使用方法
May 20 #Javascript
js判断上传文件类型判断FileUpload文件类型代码
May 20 #Javascript
jQuery 如何先创建、再修改、后添加DOM元素
May 20 #Javascript
特殊情况下如何获取span里面的值
May 20 #Javascript
jQuery基于当前元素进行下一步的遍历
May 20 #Javascript
You might like
如何在PHP中进行身份认证
2006/10/09 PHP
windows下PHP APACHE MYSQ完整配置
2007/01/02 PHP
div li的多行多列 无刷新分页示例代码
2013/10/16 PHP
PHP实现的多维数组排序算法分析
2018/02/10 PHP
JQuery 选择和过滤方法代码总结
2010/11/19 Javascript
javascript full screen 全屏显示页面元素的方法
2013/09/27 Javascript
jQuery简单实现网页选项卡特效
2014/11/24 Javascript
在页面中输出当前客户端时间javascript实例代码
2016/03/02 Javascript
详解JavaScript的另类写法
2016/04/11 Javascript
TinyMCE汉化及本地上传图片功能实例详解
2016/05/31 Javascript
浅谈JavaScript中数组的增删改查
2016/06/20 Javascript
微信JSAPI支付操作需要注意的细节
2017/01/10 Javascript
js es6系列教程 - 新的类语法实战选项卡(详解)
2017/09/02 Javascript
JS二分查找算法详解
2017/11/01 Javascript
9种使用Chrome Firefox 自带调试工具调试javascript技巧
2017/12/22 Javascript
安装vue-cli的简易过程
2018/05/22 Javascript
Node.js设置定时任务之node-schedule模块的使用详解
2020/04/28 Javascript
vue之封装多个组件调用同一接口的案例
2020/08/11 Javascript
[01:01:41]DOTA2-DPC中国联赛 正赛 PSG.LGD vs Magma BO3 第二场 1月31日
2021/03/11 DOTA
Python入门篇之数字
2014/10/20 Python
python利用urllib和urllib2访问http的GET/POST详解
2017/09/27 Python
Python OpenCV 直方图的计算与显示的方法示例
2018/02/08 Python
python 处理dataframe中的时间字段方法
2018/04/10 Python
Python selenium抓取微博内容的示例代码
2018/05/17 Python
python3.7 使用pymssql往sqlserver插入数据的方法
2019/07/08 Python
python清空命令行方式
2020/01/13 Python
PyCharm 在Windows的有用快捷键详解
2020/04/07 Python
Selenium元素定位的30种方式(史上最全)
2020/05/11 Python
Django-celery-beat动态添加周期性任务实现过程解析
2020/11/26 Python
法国票务网站:Ticketmaster法国
2018/07/09 全球购物
资产经营总监岗位职责范文
2013/12/01 职场文书
2014信息技术专业毕业生自我评价
2014/01/17 职场文书
会计专业职业规划:规划自我赢取未来
2014/02/12 职场文书
办公室年度工作总结2015
2015/05/21 职场文书
2015秋季开学演讲稿范文
2015/07/16 职场文书
Valheim服务器 Mod修改安装教程 【ValheimPlus】
2022/12/24 Servers