zoukankan      html  css  js  c++  java
  • js中的call()方法与apply()方法

        摘自:http://blog.csdn.net/chelen_jak/article/details/21021101

    在web前端开发过程中,我们经常需要改变this指向,通常我们想到的就是用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的第二参数

    其他总结:

    call方法: 
    语法:call([thisObj[,arg1[, arg2[,   [,.argN]]]]]) 
    定义:调用一个对象的一个方法,以另一个对象替换当前对象。 
    说明: 
    call 方法可以用来代替另一个对象调用一个方法。call 方法可将一个函数的对象上下文从初始的上下文改变为由 thisObj 指定的新对象。 
    如果没有提供 thisObj 参数,那么 Global 对象被用作 thisObj。 

    apply方法: 
    语法:apply([thisObj[,argArray]]) 
    定义:应用某一对象的一个方法,用另一个对象替换当前对象。 
    说明: 
    如果 argArray 不是一个有效的数组或者不是 arguments 对象,那么将导致一个 TypeError。 
    如果没有提供 argArray 和 thisObj 任何一个参数,那么 Global 对象将被用作 thisObj, 并且无法被传递任何参数。

    代码示例:

    function Animal(name) {
        this.name = name;
        this.showName = function() {
            console.log(this.name);
        };
    }
    
    function Cat(name) {
        Animal.call(this, name);
    }
    Cat.prototype = new Animal(); //prototype 属性使您有能力向对象添加属性和方法。
    
    function Dog(name) {
        Animal.apply(this, name);
    }
    Dog.prototype = new Animal();
    
    var cat = new Cat("Black Cat"); //call必须是object
    
    var dog = new Dog(["Black Dog"]); //apply必须是array
    
    cat.showName();
    dog.showName();
    
    console.log(cat instanceof Animal);
    console.log(dog instanceof Animal);
  • 相关阅读:
    「笔记」高斯消元
    函数库
    数学公式杂记
    CF1290E Cartesian Tree
    洛谷 P4027 [NOI2007] 货币兑换
    审计ThinkCMF框架任意内容包含漏洞与复现
    PHP代码审计笔记(基础篇)--命令执行漏洞
    某校园缴费平台通用0day偶然发现之路
    【转】教育src挖掘经验
    近期学习文章的整理(超级干货总结分享)
  • 原文地址:https://www.cnblogs.com/LChenglong/p/6746443.html
Copyright © 2011-2022 走看看