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

要根据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) {
            ...
        }
    });
});

时间: 2024-09-13 14:41:41

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

Javascript中判断一个值是否为undefined的方法详解_javascript技巧

前言 相信大家都知道当声明一个变量,并且没有给赋值的情况下,它的初始值是undefined.但是在javascript中,怎么检查一个值是否为undefined呢? 简单来说,在现代浏览器中,你可以安全的比较变量是否为undefined if (name === undefined) {...} 一些人反对直接使用undefined变量进行比较,因为在旧的浏览器中允许它的值被重新赋值,比如下面这样: undefined = "test" 在被重新赋值后,使用undefined指令将不能

开启Javascript中apply、call、bind的用法之旅模式_javascript技巧

我希望能够通过这篇文章,能够清晰的提升对apply.call.bind的认识,并且列出一些它们的妙用加深记忆. apply.call 在 javascript 中,call 和 apply 都是为了改变某个函数运行时的上下文(context)而存在的,换句话说,就是为了改变函数体内部 this 的指向. JavaScript 的一大特点是,函数存在「定义时上下文」和「运行时上下文」以及「上下文是可以改变的」这样的概念. 先给大家列出一段代码示例: function fruits() {} fru

JavaScript中style.left与offsetLeft的使用及区别详解_javascript技巧

如果父div的position定义为relative,子div的position定义为absolute,那么子div的style.left的值是相对于父div的值,这同offsetLeft是相同的,区别在于: 1. style.left 返回的是字符串,如28px,offsetLeft返回的是数值28,如果需要对取得的值进行计算,还用offsetLeft比较方便. 2. style.left是读写的,offsetLeft是只读的,所以要改变div的位置,只能修改style.left. 3. st

javascript中去除数组重复元素的实现方法【实例】_javascript技巧

在实际应用中,我们很多时候都可能需要去除数组中的重复元素,下面就是javascript数组去重的方法实现: <script language="javascript"> <!-- /*判断数组中是否存在某个元素的方法*/ function isExistInArr(_array, _element){ if(!_array || !_element) return false; if(!_array.length){ return (_array == _elemen

JavaScript中的公有、私有、特权和静态成员用法分析_javascript技巧

本文实例讲述了JavaScript中的公有.私有.特权和静态成员用法.分享给大家供大家参考.具体分析如下: 下面的内容是在<JavaScript.DOM高级程序设计>里面摘抄出来的,比较容易理解,特在此记录一下,便于入门Javascript的朋友们分享一下哈. 复制代码 代码如下: //构造函数 function myContructor(message){ this.myMessage = message; //私有属性 var separator = ' -'; var myOwner =

Javascript中匿名函数的调用与写法实例详解(多种)_javascript技巧

Javascript中定义函数的方式有多种,函数直接量就是其中一种.如var fun = function(){},这里function如果不赋值给fun那么它就是一个匿名函数.好,看看匿名函数的如何被调用. 方式1,调用函数,得到返回值.强制运算符使函数调用执行 (function(x,y){ alert(x+y); return x+y; }(3,4)); 方式2,调用函数,得到返回值.强制函数直接量执行再返回一个引用,引用再去调用执行 (function(x,y){ alert(x+y);

Javascript中查找不以XX字符结尾的单词示例代码_javascript技巧

首先,让我声明一下,我在写这篇文章之前花了2个多小时在弄正则表达式.悲~悲~悲~ 按照一般的思路,先来看看其他几个插找方式: 我以字符串 复制代码 代码如下: var str = "eattd gebcat gedat jadu geat beu"; 為例子. 1.以"ge"為开头的,结果应该是"gebcat, gedat, geat".因為单词以"ge"开头,则我可以放入一个新的数组供以后使用. 复制代码 代码如下: var

JavaScript中统计Textarea字数并提示还能输入的字符_javascript技巧

现在流行的Twitter等微博客网站,有一个很好的用户体验,就是在文本框中输入文字的时候,会自动统计输入的字符,并显示用户还能输入的字符,在限制了140个字的微博客中,这样的小提示可以很好的增强用户体验. 如果实现这种技术呢,我进行了一些研究,发现实现其实挺简单,几行代码就能完成输入字符统计功能,经过实际测试,其对文字的统计与Twitter等微博客的完全相同. 使用方法是,先增加一个span,用于显示剩余的字数,然后在Textarea中,加入一个onkeydown和onkeyup的事件,调用另一

JavaScript中访问id对象 属性的方式访问属性(实例代码)_javascript技巧

实例如下: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Co