• js中this的用法


    在函数内部有两个特殊对象:arguments和this,this的指向其实是非常灵活的,它会根据调用function的对象不同,导致了this的指向不同。当在全局作用域下调用函数时,this指向window。例如:

    1
    2
    3
    4
    5
    6
    7
    8
    window.color = 'red';
    var o = {color: 'blue'};
    function sayColor(){
       alert(this.color);
    }
    sayColor(); //'red'
    o.sayColor = sayColor;
    o.sayColor(); //'blue'

      我们知道this对象在执行时是基于函数的执行环境绑定的:当函数被作为某个对象的方法调用时,this指向那个对象。但匿名函数的执行环境具 有全局性,所以this指向window。但在闭包中,这一点可能不太明显。先说一下闭包吧,我的理解是在一个函数内部创建另一个函数,而内部函数可以访 问外部函数作用域中的变量,这是因为内部函数的作用域链中包含外部函数的作用域。

    复制代码
    var name = 'the window';
    var object = {
      name: 'My object',
      getFunc: function (){
         return function(){
            return this.name;
         }
      }
    };
    alert(object.getFunc()());   //'the window'
    复制代码

        看到这里,大家可能会惊讶,为什么this指向的是全局作用域。因为内部函数在搜索this和arguments时,只会搜索到其活动对象,永远不可能直接访问外部函数中的这两个变量。

    为了让闭包内的this能访问到外部作用域中的变量,我们可以在定义匿名函数之前把this附一个值,当定义闭包后就可以访问外部变量了。因为它是我们在外部函数(包含函数)中特意声明的一个变量。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    var name = 'the window';
    var object = {
      name: 'My object',
      getFunc: function (){
         var that = this;
         return function(){
            return that.name;
         }
      }
    };
    alert(object.getFunc()());   //'My object'

    this对象的获取取决于上下文;函数什么时候调用才决定了this到底引用的啥。

    也可以参考这篇博客: http://www.cnblogs.com/linfangshuhellowored/p/4248540.html

  • 相关阅读:
    MySQL-5.7.26解压版安装教程
    asp.net core 系列之Configuration
    java之初识hibernate
    java框架学习系列
    java之struts2之异常处理
    java之struts2之ajax
    java之servlet之文件下载
    列出连通集
    幸运数
    英文单词排序
  • 原文地址:https://www.cnblogs.com/niceofday/p/5045892.html
Copyright © 2020-2023  润新知