• javascript 入门——this属性的理解!


      JavaScript中函数的this对象是函数在执行时所处的作用域(例:当在网页的全局作用域中调用函数时,this对象引用的就是window)。

    例:  

    window.color = "red";
    var o = {color:"red"};
    function sayColor(){
        alert(this.color);    
    }
    sayColor();      //"red"
    o.sayColor = sayColor;
    o.sayColor();   //"blue"

      上面的sayColor()是在全局作用于中定义的,它引用this对象。由于在调用之前this的值并不确定。因此this可能在代码执行的过程中引用不同的对象。当在全局作用域中调用sayColor()时,this引用的是全局对象window;即对this.color求值会转换成对window.color求值。所以结果是“red”。而当把这个函数赋给对象o并调用o.sayColor()时,this引用的对象o,因此this.color求值会转换成对o.color求值。结果就是“blue”.

      In JavaScript, as in most object-oriented programming languages, this is a special keyword that is used within methods to refer to the object on which a method is being invoked.

      The this keyword is relative to the execution context, not the declaration context.(this与执行环境而不是声明环境有关)

    var someone = {
        name: "Bob",
        showName: function(){
            alert(this.name);
        }
    };
    
    var other = {
        name: "Tom",
        showName: someone.showName
    }
    
    other.showName();  //Tom

      this在some.showName中声明,但是在other.showName中执行,因此other.showName();执行结果为Tom。

      在没有明确执行的当前对象时,this一般指全局对象,即window。

  • 相关阅读:
    C#如何给Listbox添加右键菜单
    [GraphQL] Query Lists of Multiple Types using a Union in GraphQL
    [GraphQL] Query GraphQL Interface Types in GraphQL Playground
    [GraphQL] Reuse GraphQL Selection Sets with Fragments
    [Dart] final vs const
    [GraphQL] Set variable and default value & alias
    [置顶] 【Git入门之十一】标签管理
    poj 3182 The Grove bfs
    hdu1166敌兵布阵
    <WinForm_1>初识WinForm编程
  • 原文地址:https://www.cnblogs.com/wenyi1992/p/5257954.html
Copyright © 2020-2023  润新知