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的走

     

     

     

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值