[关闭]
@Bios 2018-12-10T08:41:57.000000Z 字数 1780 阅读 658

this关键字 指向问题

js


this:上下文,会根据执行环境变化而发生指向的改变.

1.单独的this,指向的是window这个对象

  1. alert(this); // this -> window

2.全局函数中的this

  1. function demo() {
  2. alert(this); // this -> window
  3. }
  4. demo();

在严格模式下,this是undefined.

  1. function demo() {
  2. 'use strict';
  3. alert(this); // undefined
  4. }
  5. demo();

3.函数调用的时候,前面加上new关键字

所谓构造函数,就是通过这个函数生成一个新对象,这时,this就指向这个对象。

  1. function demo() {
  2. //alert(this); // this -> object
  3. this.testStr = 'this is a test';
  4. }
  5. let a = new demo();
  6. alert(a.testStr); // 'this is a test'

4.用call与apply的方式调用函数

  1. function demo() {
  2. alert(this);
  3. }
  4. demo.call('abc'); // abc
  5. demo.call(null); // this -> window
  6. demo.call(undefined); // this -> window

5.定时器中的this,指向的是window

  1. setTimeout(function() {
  2. alert(this); // this -> window ,严格模式 也是指向window
  3. },500)

6.元素绑定事件,事件触发后,执行的函数中的this,指向的是当前元素

  1. window.onload = function() {
  2. let $btn = document.getElementById('btn');
  3. $btn.onclick = function(){
  4. alert(this); // this -> 当前触发
  5. }
  6. }

7.函数调用时如果绑定了bind,那么函数中的this指向了bind中绑定的元素

  1. window.onload = function() {
  2. let $btn = document.getElementById('btn');
  3. $btn.addEventListener('click',function() {
  4. alert(this); // window
  5. }.bind(window))
  6. }

8.对象中的方法,该方法被哪个对象调用了,那么方法中的this就指向该对象

  1. let name = 'finget'
  2. let obj = {
  3. name: 'FinGet',
  4. getName: function() {
  5. alert(this.name);
  6. }
  7. }
  8. obj.getName(); // FinGet
  9. ---------------------------分割线----------------------------
  10. let fn = obj.getName;
  11. fn(); //finget this -> window

腾讯笔试题

  1. var x = 20;
  2. var a = {
  3. x: 15,
  4. fn: function() {
  5. var x = 30;
  6. return function() {
  7. return this.x
  8. }
  9. }
  10. }
  11. console.log(a.fn());
  12. console.log((a.fn())());
  13. console.log(a.fn()());
  14. console.log(a.fn()() == (a.fn())());
  15. console.log(a.fn().call(this));
  16. console.log(a.fn().call(a));

答案

1.console.log(a.fn());
对象调用方法,返回了一个方法。
# function() {return this.x}

2.console.log((a.fn())());
a.fn()返回的是一个函数,()()这是自执行表达式。this -> window
# 20

3.console.log(a.fn()());
a.fn()相当于在全局定义了一个函数,然后再自己调用执行。this -> window
# 20

4.console.log(a.fn()() == (a.fn())());
# true

5.console.log(a.fn().call(this));
这段代码在全局环境中执行,this -> window
# 20

6.console.log(a.fn().call(a));
this -> a
# 15

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注