JavaScript函数内部this的指向

JavaScript函数内部this的指向

JavaScript函数

JavaScript函数是被设计为执行特定任务的代码块,会在某代码调用它时被执行,方便重复使用

函数的定义和调用

函数声明:
function fn(a, b) {
    
    
    var num = a+b
    console.log(num)
}
//调用函数
fn(1, 2) //3
函数表达式:
var fn = function(a, b) {
    
    
    var num = a+b
    console.log(num)
}
//调用函数
fn(1, 2) //3
Function()构造函数:
var fn = new Function('a, b','var num = a+b; console.log(num)')
//调用函数
fn(1, 2) //3
自调用函数:
//自动调用函数
(function(a, b) {
    
    
    var num = a+b
    console.log(num)
})(1, 2) //3
ES6箭头函数:
var fn = (a, b) => {
    
    
    var num = a+b
    console.log(num)
}
//调用函数
fn(1, 2) //3

函数内部this的指向

1.普通函数的直接调用

this指向 window
function fn() {
    
    
    console.log(this) //window
}
fn()

2.函数作为对象的属性去调用

this指向 该对象
var a = 123
var obj = {
    
    
    a: 456,
    fn1: function () {
    
    
        console.log(this.a) //456
    }
};
obj.fn1()

3.构造函数通过new关键字调用

this指向 当前创建的对象
function Fn(a, b) {
    
    
    this.a = a
    this.b = b
}
var obj = new Fn(1, 2)
console.log(obj.a) //1
console.log(obj.b) //2

4.函数在定时器中调用

this指向 window
//当定时器达到指定时间,浏览器会直接调用定时器中的函数
setTimeout(function() {
    
    
    console.log(this) //window
}, 500)

5.函数作为方法去调用

this指向 调用者
function Fn(a, b) {
    
    
    this.a = a
    this.b = b
}
Fn.prototype.get = function () {
    
    
    console.log(this.a, this.b)
}
var fn1 = new Fn(1, 2)
var fn2 = new Fn(3, 4)
fn1.get() //1 2
fn2.get() //3 4

6.函数作为事件处理程序去调用

this指向 事件源
document.querySelector('html').onclick = function() {
    
    
    console.log(this) //<html></html>
}

7.ES6箭头函数

this指向 定义时的对象,箭头函数没有自己的this,它的this指向定义时所在的对象,且它的指向无法改变
//定时器中的普通函数this指向window
function Fn1() {
    
    
    this.a = 1
    setTimeout(function(){
    
    
        console.log(this) //window
    }, 10)
}  
var fn3 = new Fn1() 

//定时器中的箭头函数this指向外层代码块的this,即定义时的对象
function Fn2() {
    
    
    this.a = 1
    setTimeout(() => {
    
    
        console.log(this) //Fn2{a: 1}
    }, 10)
}  
var fn4 = new Fn2()

改变函数内部this指向的方法

1.call方法

函数名.call(借用者, 参数…)
function fn(a, b) {
    
    
    this.a = a
    this.b = b
}  
var obj = {
    
    }
//被借用的函数会立即执行,函数内部this指向借用者
fn.call(obj, 1, 2)
console.log(obj) //{a:1, b:2}

2.apply方法

函数名.apply(借用者, [参数…])
function fn(a, b) {
    
    
    this.a = a
    this.b = b
}  
var obj = {
    
    }
//被借用的函数会立即执行,函数内部this指向借用者,参数为数组形式
fn.apply(obj, [1, 2])
console.log(obj) //{a:1, b:2}

3.bind方法

函数名.bind(借用者, 参数…)
function fn(a, b) {
    
    
    this.a = a
    this.b = b
}  
var obj = {
    
    }
//被借用的函数不会立即执行,返回一个新的函数,需要调用新函数,函数内部this指向借用者
fn.bind(obj, 1, 2)()
console.log(obj) //{a:1, b:2}

call,apply,bind对比

相同点:
  1. 都是用来改变函数内部this的指向
  2. 都可以传递参数,第一个参数都是this要指向的对象(借用者),当为null、undefined的时候,默认指向window
不同点:
  1. apply的参数是以数组的形式,call和bind的参数是一个个传递
  2. call和apply的函数会立即执行,bind返回一个新函数,使用时需要调用

猜你喜欢

转载自blog.csdn.net/weixin_45426836/article/details/103757179
今日推荐