• js中this的指向


    函数中this的指向是不确定的,只有在函数执行时才能确定,它指向调用该函数的对象

    var a = 'a'
    var b = 'b'
    function f(){
      console.log(this)  //window
      console.log(this.a) //a
      console.log(this.b) //b
      console.log(this.c) //undefined  this指向window,window中没有c
      var a = 'aa'
      b = 'bb'
      var c = 'cc'
      console.log(this.a) //a  函数中定义变量a,但是this.a为window.a 
      console.log(this.b)//bb    window中的变量b在函数体内被改变  
      console.log(this.c)   //undefined  this指向window,window中没有c
      console.log(window.a) //a
      console.log(window.b) // bb  window中的变量b在函数体内被改变
      console.log(window.c)  //undefined  this指向window,window中没有c

      console.log(a)  //aa
      console.log(b) //bb
      console.log(c)  //cc

    }
    f()

     这里调用函数f的对象是window,函数内部的this为window

    var o = {
        name: 'lll',
        getName:function(){
            console.log(this.name)
        }
    }
    o.getName()  // lll
    var m = o.getName
    m()    //此时this指向window
    

     构造函数

    function P(){
        this.name = 'ppp'
    }
    var p = new P()
    console.log(p.name)  

    new关键字改变this的指向

  • 相关阅读:
    Visual Studio 2015 开发 ASP.NET 5
    全新的membership框架Asp.net Identity
    VS2013下实现移动端的跨平台开发
    用SQL语句,删除掉重复项只保留一条
    SOA IN Real World
    Asp.net负载均衡之Session
    C#时常需要调用C++DLL
    C# 支付宝接口
    好代码是怎么炼成的
    ASP.net 服务器监控
  • 原文地址:https://www.cnblogs.com/lhyhappy365/p/10365046.html
Copyright © 2020-2023  润新知