zoukankan      html  css  js  c++  java
  • call和applay的使用

    1. call方法
    • 调用一个对象的一个方法,以另一个对象替代当前的对象。说明白一点,其实就是更改对象的内部指针,即改变对象this的指向内容;参考代码如下:

      

    function Obj(){
    this.value="obj的变量";
    } var value="the window"; function fn(){
    alert(this.value);
    } window.fn(); //the window fn.call(window); //the window fn.call(new Obj()); //obj的变量

     

    var fun = new function(){
       this.a="fun";
    
    }
     var  myfun =function(x){
       var a ="myfun";
       alert(this.a);
    alert(x)
    }
    myfun.call(fun,'var ')//fun   var 
    

      

    最后,分析结果

    1、全局对象window调用函数fn,this指向window对象,因此this.value为the window

    2、函数fn调用call方法,this默认指向第一个参数window对象,因此this.value也为the window

    3、函数fn调用call方法,this默认指向第一个参数new Obj(),即Obj的对象,因此this.value为Obj的成员变量obj的变量

    5、函数myfun调用call方法,this默认指向第一个参数fun函数对象,因此this.value为this.a,即fun

    6、函数myfun调用call方法,第二个参数属于函数对象myfun的参数,因此alert(x)为第二个参数var

    对于call和apply两者在作用上是相同的。但两者在参数上是不同的。对于第一个参数都一样,但对于第二个参数,apply传入的是一个参数数组,也就是将多个参数组成一个数组传入,而call则作为call的参数传入:

    fun.call(fun1,var1,var2,var3)

    fun.apply(fun1,[var1,var2,var3])

  • 相关阅读:
    LeetCode100——same tree
    Stl——Vector.erase()用法
    xor异或逻辑运算
    爬楼梯问题——迭代or递归
    简单博弈论取石子
    纪念我的leetcode开门之旅
    JiuDuOj——1049
    [Codeforces 872]比赛记录
    [BZOJ 4563]放棋子
    10.14
  • 原文地址:https://www.cnblogs.com/tfl123/p/7425279.html
Copyright © 2011-2022 走看看