zoukankan      html  css  js  c++  java
  • js中关于this的理解

    常见:在普通函数中的this,指向 全局

    function thisObj(name){
        this.name = name;
        console.log(this);
    }

    但是在严格模式下的函数,this指向 underfined.

    混淆点.内部函数中的this指向:

    var numbers = {
       numberA: 5,
       numberB: 10,
       sum: function() {
         console.log(this === numbers); // => true
         function calculate() {
           // this is window or undefined in strict mode
           console.log(this === window); // => true
           console.log(this === numbers); // => false;
           return this.numberA + this.numberB;
         };
         return calculate();
       }
    };
    numbers.sum();

    在上述numbers对象中,sum函数是numbers对象的方法。所以sum函数中的this指向numbers对象。

    但是在内部函数calculate中,我们如果以为this也是指向numbers对象那就打错特错了。

    在这里该内部对象是一个函数调用,并不是对象的方法。所以calculate中的this指向 window。

    所以为了避免calculate中的this指向错误。要进行如下修改,将this值指向numbers对象。

    var numbers = {
       numberA: 5,
       numberB: 10,
       sum: function() {
         console.log(this === numbers); // => true
         function calculate() {
           // this is window or undefined in strict mode
           console.log(this === window); // => true
           console.log(this === numbers); // => false;
           return this.numberA + this.numberB;
         };
         return calculate.call(this);//return calculate();
       }
    };
    numbers.sum();

    混淆点.从Object中分离的方法

    function People(name){
        this.name = name;
        this.action = function(){
            console.log("this是否等于window " + this === window)
            console.log(this.name)
        }
    }
    var xiaoA = new People('xyf');
    var zz = xiaoA.action;
    zz();  //输出错误
    xiaoA.action() // 输出 xyf
    setInterval(xiaoA.action,500000);//错误
    setInterval(xiaoA.action.bind(xiaoA),500000);//循环输出 xyf
    这里要注意  如果直接输出 xiaoA.action();是可以正确输出的。但是当我们将xiaoA.action赋值给变量zz之后。该action方法就从原来的Object中分离了。这时候的this指向全局变量。setInterval定时器也会产生这样的问题。如果要正确显示需要用bind重新绑定对象。
    var zz =xiaoA.action.bind(xiaoA);
    zz(); //输出 xyf

    apply调用

    apply()是函数对象的一个方法,它的作用是改变函数的调用对象,它的第一个参数就表示改变后的调用这个函数的对象。因此,this指的就是这第一个参数。apply()的参数为空时,默认调用全局对象。

  • 相关阅读:
    linux 命令——48 watch (转)
    linux 命令——47 iostat (转)
    linux 命令——46 vmstat(转)
    linux 命令——45 free(转)
    linux 命令——44 top (转)
    linux 命令——43 killall(转)
    linux 命令——42 kill (转)
    linux 命令——41 ps(转)
    linux 命令——40 wc (转)
    Java for LeetCode 068 Text Justification
  • 原文地址:https://www.cnblogs.com/enmeen/p/5714892.html
Copyright © 2011-2022 走看看