zoukankan      html  css  js  c++  java
  • call 和 apply 方法区别

    在js中call和apply它们的作用都是将函数绑定到另外一个对象上去运行,两者仅在定义参数方式有所区别,下面我来给大家介绍一下call和apply用法。

    在web前端开发过程中,我们经常需要改变this指向,通常我们想到的就是用call方法,但是对于call的理解很多人不是很清晰,那么下面小编就给大家详细说一说call和apply的详细知识

    一、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

    三、实现继承

    如下例子:

     代码如下 复制代码

    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

    四、apply用法

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

    a.call(b,arg1,arg2…)

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

  • 相关阅读:
    生产者消费者模式
    Linux提权(capabilities)
    协程
    xpath常用
    iframe 练习
    python 实现数据库中数据添加、查询与更新
    web网站压力/性能测试经验分享
    AttributeError: module 'applescript' has no attribute 'app'解决方案
    pip3: error: can't exec '/usr/local/bin/pip3' (errno=No such file or directory)报错解决方案
    看了这篇双十一抢购攻略?喜欢的东西还能抢不到?
  • 原文地址:https://www.cnblogs.com/weibozeng/p/4053565.html
Copyright © 2011-2022 走看看