在前面的例子中,获取this.name掉败,因为函数的this个是undefined,它与办法loop()的不合。 有三种办法可以修改this。
修改1: that = this。 将它分派给一个没有被掩蔽的变量(另一个风行名称是self)并应用该变量。
- 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的第二个参数。 此办法具有第二个参数,this值将作为此值传递给回调函数。
- loop: function () {
- 'use strict';
- this.friends.forEach(function (friend) {
- console.log(this.name+' knows '+friend);
- }, this);
- }
大年夜概念上讲,我认为通俗函数没有它本身的this,并且想到上述修复是为了保持这种设法主意。 ECMAScript 6经由过程箭头函数支撑这种办法 - 没有它们本身的this。 在如许的函数琅绫擎,你可以自由应用this,因为不会被樊篱:
推荐阅读
有奖调研 | 人脸辨认功能在互联网行业认知度情况经由过程应用法度榜样级其余感知和洞察,为微办事带来编排和主动化的优势 微软的 Azure Service Fabric 的官方博客在2017.3.2>>>详细阅读
本文标题:JavaScript中this的运行机制及爬坑指南
地址:http://www.17bianji.com/lsqh/40750.html
1/2 1