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])

  • 相关阅读:
    6,Django之视图层
    5,Django的路由层
    4,django系列django简介
    3,django系列web框架
    2,django系列之http协议
    1.django系列web应用
    各版本数据库的默认端口号
    vue v-for 渲染完成回调
    linux 下 The valid characters are defined in RFC 7230 and RFC 3986
    linux 下启动tomca慢问题
  • 原文地址:https://www.cnblogs.com/tfl123/p/7425279.html
Copyright © 2011-2022 走看看