js高级-函数的四种调用模式

1、对象方法调用模式  方法内部的this指向当前调用者的对象d

  定义类 (构造函数)

  function Dog (dogName){

    //创建一个空对象   让空对象==this

    this.name =  dogName;

    this.age = 0;

    this.run = function(){

      console.log(this.name + 'is running...')

    }

    //如果函数当做构造函数来调用(new)并且没有返回任何数据的时候 默认返回this

  }

  var d= new Dog('wangwang');

  d.run();

 

2、构造器调用模式 new

  function Cat(){

    this.name = "cat"

    this.age = 19;

    this.run = function(){

      console.log(this.name + 'is running...')

    }

  }

  var cat = new Cat();  //构造函数调用模式

  cat.run()  //方法调用模式

 

3、函数调用模式

  function f(a,b){

    console.log(a+''+b)

    console.log(this)  window

  }

  f(2,3)

  习题

  function Dog(){

    this.age = 19;

    console.log(this)

  }

  Dog()  //window  函数调用模式

  var d = new Dog();  //d  构造函数调用模式

 

4、call apply 调用模式

  function sum(a,b){

    console.log(this)

    return a+b

  }

  sum(1,2)  //this->window

  var t = {

    name:'laoma'

  }

  var m = sum.call(t,2,3)  //t 作为this传到函数里  sum方法里面的this 指向t   sum不是直接调用了 而是用call去调用这个sum方法 同时修改了this指向

          sum.apply(t,[2,3])

  console.log(m)

  //如果是number string 转化成包装类型 如果是null 还是原始的

  sum.call(null,2,3)  //window

  sum.call(undefined,2,3)  //window

 

  //习题

  借用Math.min方法 求数组最小值 [2,9,33]

  Math.min.apply(null,[2,9,33])

  把一个类数组转化成真数组  t = [1,true]

  var t = {}

  t[0] = 1;

  t[1] = true;

  t.length = 2;

  Array.prototype.slice.call(t,0)

posted @ 2018-05-25 10:46  suanmei  阅读(119)  评论(0编辑  收藏  举报