javascript学习笔记08(length,call和apply)

length,call和apply

    <script type="text/javascript">
    function fn1() {
        
    }
    
    function fn2(num1,num2) {
        
    }
    
    function fn3(num1){
        
    }
    //函数的length就表示该函数所期望的参数值
    alert(fn1.length);//0
    alert(fn2.length);//2
    alert(fn3.length);//1
    </script>

 

<script type="text/javascript">
    function sum(num1,num2) {
        return num1+num2;
    }
    
    function callSum1(num1,num2) {
        //使用sum这个函数来完成一次调用,调用的参数就是callSum1这个函数的参数
        //apply的第二个参数表示一组参数数组
        return sum.apply(this,arguments);
    }
    
    function callSum2(num1,num2) {
        //关键就是第二个参数是数组
        return sum.apply(this,[num1,num2]);
    }
    alert(callSum1(12,22));
    alert(callSum2(22,32));
    
    function callSum3(num1,num2) {
        //call是通过参数列表来完成传递,其他和apply没有任何区别
        return sum.call(this,num1,num2);
    }
    alert(callSum3(22,33));
    </script>
</body>

 

<script type="text/javascript">
    /**
     * 当需要创建一个类的时候,设置类的属性和方法需要通过this关键字来引用
     * 但是特别注意:this关键字在调用时会根据不同的调用对象变得不同
     */
    
    var color = "red";
    function showColor() {
        alert(this.color);
    }
    /**
     * 创建了一个类,有一个color的属性和一个show的方法
     */
    function Circle(color) {
        this.color = color;
    }
    
    var c = new Circle("yellow");
    
    showColor.call(this);//使用上下文来调用showColor,结果是red
    showColor.call(c);//上下文对象是c,结果就是yellow
    /**
     * 通过以上发现,使用call和apply之后,对象中可以不需要定义方法了
     * 这就是call和apply的一种运用
     */
    </script>

posted @ 2015-05-21 08:50  暴走骑士  阅读(142)  评论(0编辑  收藏  举报