zoukankan      html  css  js  c++  java
  • js 改变this指向的三种方法,call() apply() bind()

    this是JS中的一个关键字,它始终指向一个对象,this是一个指针。

    this的指向不是由定义this决定的,而是随着脚本的解析自动赋值的。

    一、全局作用域下:this始终指向window对象

    二、函数作用域下:函数被谁调用,this就指向谁

    三、对象中的函数作用域下:this指向该方法所属的对象

    四、在构造函数中:this始终指向新对象

    五、自执行函数中:this指向window

    六、箭头函数中:this是在定义是绑定到了父级对象上,不是在执行过程中绑定的。

    更改this指向方法:

    1. call(thisObj, 参数1,参数2 ...)

    var person = {
        name: 'zhangsan',
        age: 20
    }
    
    function say(x, y){
        console.log(this.name)
        console.log(this.age)
        console.log(x, y)
    }
    
    say.call(person, 1, 2)
    // zhangsan
    // 20
    // 1 2

    2. apply(thisObj, [参数1,参数2 ...])

    var person = {
        name: 'zhangsan',
        age: 20
    }
    
    function say(x, y){
        console.log(this.name)
        console.log(this.age)
        console.log(x, y)
    }
    
    say.apply(person, [1, 2])
    // zhangsan
    // 20
    // 1 2

    3.bind(thisObj, 参数1,参数2 ...)

    var person = {
        name: 'zhangsan',
        age: 20
    }
    
    function say(x, y){
        console.log(this.name)
        console.log(this.age)
        console.log(x, y)
    }
    
    say.bind(person, 1, 2)();
    // zhangsan
    // 20
    // 1 2
  • 相关阅读:
    02方法 课后作业1
    HDU 1518
    POJ 2406
    HDU 1953
    HDU 1272
    POJ -- 3842
    POJ -- 3233 求“等比矩阵”前n(n <=10^9)项和
    POJ ---3070 (矩阵乘法求Fibonacci 数列)
    POJ --- 3613 (K步最短路+矩阵快速幂+floyd)
    POJ --- 2918 求解数独
  • 原文地址:https://www.cnblogs.com/front-boy/p/12698930.html
Copyright © 2011-2022 走看看