JavaScript學習筆記之函數概述

一、函數調用方法

  1. 直接調用:foo();
  2. 對象方法:o.method();
  3. 構造器:new Foo();
  4. call/apply/bind:func.call(o);

二、創建函數的方式

  1. 函數聲明
    function add(a,b){
      //內容
    }

     

  2. 函數表達式
    var add = function(a,b){}   //賦值函數表達式
    
    (function(){
    })();                //立即執行函數表達式
    
    var add = function foo(a,b){
     // 內容
    }                     // 命名式函數表達式

     

  3. 兩者區別在於變量提升。

Function構造器(函數構造器)

var func = new Function('a','b','console.log(a+b);');
func(1,2);    //3

var func =  Function('a','b','console.log(a+b);');
func(1,2);    //3

//本質上無區別

 三、this

  1. 全局this。
    // 瀏覽器下
    console.log(this === window)    // true
    
    function f1(){ return this; }    //瀏覽器下指向window,node裏面指向global
     function f2() {
       "use strict";
    return this;             //嚴格模式下指向undefined
    }

     

  2. 作爲對象方法的函數的this。

    var o ={
      prop: 37,
      f: function() {
        return this.prop;
    }
    };
    console.log(o.f());   // 37
    
    

     

  3. 對象原型鏈上的this。

  4. 構造器中的this。

    function MyClass(){
      this.a = 37;
    }                // 正常情況下this指向window
    
    
    var o = new MyClass(){
      console.log(o.a);   //如果使用new把其作爲構造器去調用的話,this會指向一個空的對象,並且這個對像的原型會指向MyClass.prototype,並且this會作爲返回值給構造器中。
    }
    
    
    function C2(){
      this.a =37;
      return {a:38};
    }
    
    o = new C2();
    console.log(o.a); //38 此時返回的是return的對象,不是this

     

  5. call/apply方法與this。

    function add(c,d){
      return this.a + this.b + c+d;
    }
    
    var o = {a:1,b:3};
    add.call(o,5,7);   // 1+3+5+7 = 16
    add.apply(o,[10,20]);   // 1+3+10+20 = 34
    function bar() {
       console.log(Object.prototype.toString.call(this));
    }
    bar.call(7);   //"[object Number]"
    
    
    //call,apply傳參方式不同,call扁平化傳入,apply作爲數組傳入。
    

     

  6. bind方法。

    function f(){
      return this.a;
    }
    
    var g = f.bind({a:"test"});
    console.log(g()); //test
    var o = { a:37,f:f,g:g};
    console.log(o.f(),o.g()); // 37,test
    
    //使用bind綁定之後,this會按照bind的走

     

     

     

 

 

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章