重温js——函数表达式和this

142 阅读2分钟

这是我参与8月更文挑战的第8天,活动详情查看:8月更文挑战

函数表达式

js 中,函数也是一个数据,在语法上,函数可以用于任何需要数据的地方

JS中,函数是一等公民,函数还可以放到变量当中。

var a =  function test () {
			// 代码块
}

上面这一块代码是一个函数表达式,test 不会提升到全局。意思是创建一个函数,将其赋值给变量 a

重温js——函数表达式和this

我们知道a 里面保存的是函数的引用地址,那么函数的调用是使用 () 来进行调用,保存到某个变量中的函数地址,直接 a() 就能调用该函数了。

任何可以出现数据的地方,函数就可以出现,函数是引用值类型。

this 关键字

this 是无法赋值的。

  1. 在全局作用域中,this指向全局,浏览器环境中指向window,node环境非严格模式下指向glob,严格模式下指向undefined。
  2. 函数作用域中,取决于函数的调用情况

1. 函数是直接调用的,this 是指向全局

重温js——函数表达式和this

2. 通过对象来调用,还是对象的一个属性,格式为 对象.属性(), 这种情况,this 是指向对象本身

重温js——函数表达式和this

3. 如果对象中的函数保存到外部,那this就指向当前外部所处的环境,对象中指向对象,全局的话就指向全局。

重温js——函数表达式和this

4. 函数如果使用 new 的方式来调用, this 指向当前的当前调用的实例对象

function main(){
    this.aad = 234;
    this.def = function(){
                console.log(this);
            };
    this.foo = function(){
            console.log(this === xxx);
        };
    this.xoo = function(){
            console.log(this === main);
        };
}
var xxx = new main();
xxx.def(); 
xxx.foo();
xxx.xoo();

5. 箭头函数调用,this 指向外部的环境。

  var obj = {
  a: 1,
  b: () => {
    console.log(this, '-b----')
  },
  c: {
    e: 1232,
    d:function(){
       console.log(this, '-d----')
      }
  }
}
obj.b();
obj.c.d();

function test(){
  
  var a = () => {
    console.log(this,'------函数里面的箭头函数指向')
  }
  a();
}

test();

重温js——函数表达式和this

6. dom 中的this 指向dom(事件处理对象).

 <!DOCTYPE html>
 <html lang="en">
 <head>
   <meta charset="UTF-8">
   <meta name="viewport" content="width=device-width, initial-scale=1.0">
   <title>Document</title>
 </head>
 <body>
   <div onclick="console.log(this)" style="width: 100px;height: 100px;background-color: aliceblue;"></div>
 </body>
 
 </html>

重温js——函数表达式和this

7. 使用bind、apply、call手动绑定this对象

function hello(thing) {
 console.log(this + " says hello " + thing);
}

hello.call("Yehuda", "world") 

重温js——函数表达式和this

本文使用 文章同步助手 同步