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)

转载于:https://www.cnblogs.com/suanmei/p/9087272.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值