zoukankan      html  css  js  c++  java
  • Math.min() / Math.max() 使用方法

    首先弄懂apply 和 call 都是js函数自带的方法。区别如下:

    apply和call的用法只有一个地方不一样,除此之外,其他地方基本一模一样

    1. a.call(b,arg1,arg2…)

    2. apply(b,[arg1,arg2]) //apply只有2个参数,它将call的参数(arg1,arg2…)放在一个数组中作为apply的第二参数

    例1:apply的第一个参数传递作用域,第二个参数传递数组。

    Math.min.apply(null, [1, 2, 3]) 等价于 Math.min(1, 2, 3)    // 1
    

    下面再来看call有哪些用途:

    一:实现继承

    function Animal(name)
    {
        this.name=name;
        this.showName=function()
        {
            alert(this.name)
        }
    }
    function Cat(name)
    {
        Animal.call(this,name); //将Animal应用到Cat上,因此Cat拥有了Animal的所有属性和方法
    }
    var cat = new Cat(“Black Cat”);
    cat.showName(); //浏览器弹出Black Cat
    

      

    二.call方法的定义:

    大家在百度里面可以搜索call,关于call的定义都很拗口。在我的理解,a.call(b,arg1,arg2..)就是a对象的方法应用到b对象上。例如如下例子:

    function add(a,b)
    {
        alert(a+b);
    }
    function reduce(a,b)
    {
        alert(a-b);
    }
    add.call(reduce,1,3) //将add方法运用到reduce,结果为4

    三.call可以改变this指向

    function b()
    {
        alert(this)
    }
    b(); //window
    b.call(); //window
    b.call(“a”,2,3); //a
    

    再看一个复杂的例子:

    function Animal()
    {
        this.name=”animal”;
        this.showName=function()
        {
            alert(this.name)
        }
    }
    function Cat()
    {
        this.name=”cat”;
    }
    var animal = new Animal(); //原型继承
    var cat = new Cat();
    animal.showName(); //结果为animal
    animal.showName.call(cat); //原本cat没有showName方法,但是通过call方法将animal的showName方法应用到cat上,因此结果为 cat
    

      

      

  • 相关阅读:
    java 集合类 *****
    Vector & ArrayList Hashtable & HashMap ArrayList & LinkedList
    全排列 递归实现
    JAVA虚拟机、Dalvik虚拟机和ART虚拟机简要对比
    数据库之“视图”
    Qt开发经验小技巧1-10
    Qt编写安防视频监控系统14-本地回放
    Qt编写安防视频监控系统13-视频存储
    Qt编写图片及视频TCP/UDP网络传输
    Qt编写气体安全管理系统29-跨平台
  • 原文地址:https://www.cnblogs.com/mmzuo-798/p/7411296.html
Copyright © 2011-2022 走看看