18_javascript中的this都有哪些用法

2020-04-14  本文已影响0人  沐向

一、this的用法

1、基本概念

简而言之,就是function的this永远指向调用它的对象。而鉴于JS所谓的“万物皆对象”,这个this因此可以是任何物件,比如Global对象。

2、使用方法

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

alert(this); // this -> window

(2)全局函数中的this

function test(){     
    this.x = 1;   
    alert(this); // this -> window
    alert(this.x); // 1    
}   
test(); 

在严格模式下,this是undefined.

function demo() {
 'use strict';
  alert(this); // undefined
}
demo();

(3)作为构造函数调用,this 指代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'

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

let name = 'finget'
let obj = {
 name: 'FinGet',
 getName: function() {
    alert(this.name);
 }
}
obj.getName(); // FinGet

(5)用call与apply的方式调用函数

作用是改变函数的调用对象,此方法的第一个参数为改变后调用这个函数的对象,this指代第一个参数

var x = 0;
function test() {
  alert(this.x);
}
var o = {};
o.x = 1;
o.m = test;
o.m.apply(); //0
//apply()的参数为空时,默认调用全局对象。因此,这时的运行结果为0,证明this指的是全局对象。如果把最后一行代码修改为

o.m.apply(o); //1

(6)定时器中的this,指向的是window

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

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

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

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

window.onload = function() {
 let $btn = document.getElementById('btn');
 $btn.addEventListener('click',function() {
    alert(this); // window
 }.bind(window))
}

二、面试题

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));

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
上一篇 下一篇

猜你喜欢

热点阅读