javascript之函数

2019-06-21  本文已影响0人  Mcq

函数基础

创建和调用函数

函数的参数

函数的返回值

作用域

变量提升

匿名函数和自调用函数

一. 函数也是对象

==var 变量名 = new Function('参数1','参数2',...,'函数体中的代码');== 

二. 函数内部this的指向

​ 在此,this是在函数内部研究

​ 函数内部的this不是在函数定义时决定的,而是在函数调用执行时决定的。

2.1 普通函数中this的指向

      function fn() {
        console.log(this);
      }
     fn();  // window

      var fn = function(){
        console.log(this);
      };
      fn(); // window

      (function(){
        console.log(this);
     })(); // window

     function fn1() {
        var fn2 = function() {
          console.log(this);
      }
      fn2(); // window
     }
      fn1();

2.2 定时器中this的指向

     【定时器中的this指向window】
      setTimeout(function(){
        console.log(this);
      },10);

2.3 构造函数中this指向

this指向当前创建的对象。 要去理解new关键字的创建过程

    function Student(name,age) {
      this.name = name;
      this.age = age;
    }
    Student.prototype.sayHi = function() {
      console.log('我叫' + this.name);
    };
    var stu1 = new Student('张三',18);
    var stu2 = new Student('李四',18);

2.4 方法中this指向

this指向方法的调用者。

    function Student(name,age) {
      this.name = name;
      this.age = age;
    }
    Student.prototype.sayHi = function() {
      console.log('我叫' + this.name);
    };
    var stu1 = new Student('张三',18);
    var stu2 = new Student('李四',18);


    // 【在调用一个方法时→对象.方法名(); 方法内部this指向调用者】
    stu1.sayHi();  // 张三
    stu2.sayHi();  // 李四

2.5 事件处理程序中this指向

this指向事件源。 事件触发后(函数才会执行)才知道

    // 【事件处理程序→ this指向事件源】
    document.onclick = function() {
      console.log(this);  // document
    };

三. 改变this的指向

3.1 call方法

3.2 apply方法

3.3 bind方法

应用

  1. 伪数组借用数组的push方法实现增加

  2. 使用Math对象max方法取出数组中的最大数字

  3. 作业:伪数组借用数组的reverse方法实现反转

四.函数的其他属性

上一篇下一篇

猜你喜欢

热点阅读