zoukankan      html  css  js  c++  java
  • 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的指向

  • 相关阅读:
    Redis 查看、删除keys
    gitlab 备份和恢复
    gitlab的搭建
    certbot 域名续期及证书查看
    晴天(周杰伦)
    SSH Permission denied (publickey,gssapi-keyex,gssapi-with-mic)
    jenkins miaration section 1
    jenkins 忘记管理员密码
    Yangk's-树状数组 模板
    codeforces-977F-Consecutive Subsequence【动态规划】
  • 原文地址:https://www.cnblogs.com/lhyhappy365/p/10365046.html
Copyright © 2011-2022 走看看