javascript當(dāng)中call()和apply()用法

call()和apply()
馬克-to-win:call是在特定的作用域中調(diào)用函數(shù)。



例 3.13.1

<html>
<head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
    <title>

    </title>
    <script type="text/javascript">
        function A(name) {
            this.name = name;
        }
         A.prototype.info = function()
         {
         /*如果下局解開屏蔽,最后結(jié)果則打印出就為A,結(jié)論就是在call時(shí),先在A里找this.name,如果找不著,則用b環(huán)境里找,現(xiàn)在A的構(gòu)造函數(shù)從來(lái)沒有執(zhí)行過,所以最后用的是B環(huán)境的name,見下一個(gè)例子*/
                //this.name="A";
                return "A的名字是 "+this.name;
         }


        function B(agev)  {
            this.age=agev;
            this.name="I am B"
        }
            var b = new B(2);
    var tmp =A.prototype.info;
    document.writeln(tmp.call(b));

    var zhanwei="zhanwei";

    </script>
</head>
<body>




輸出結(jié)果:
A的名字是 I am B


<html>
<head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
    <title>

    </title>
    <script type="text/javascript">
        function A(name,col) {
 /*實(shí)參一個(gè),但形參2個(gè),所以最后一個(gè)參數(shù)color為undefined,id和name都有,所以是把B給沖了的,但age是用了B的*/
            this.color=col;
            this.id="a";
            this.name = name;
            return "A(name) 名字是 "+this.id+this.name+this.age+this.color;
        }
         A.prototype.info = function()
         {
                return "名字是 "+this.name;
         }
        A.prototype.country = "China";

        function B(agev)  {
            this.id="b";
            this.age=agev;
            this.name="this is B"
        }
            var b = new B(2);

    document.writeln(A.call(b, "馬克-to-win"));
    var zhanwei="zhanwei";

    </script>
</head>
<body>



結(jié)果:
A(name) 名字是 a馬克-to-win2undefined




例 3.13.2
<script>
/*
他們的用途相同,都是在特定的作用域中調(diào)用函數(shù)。screenX是window的一個(gè)field。
 3、接收參數(shù)方面不同,apply()接收兩個(gè)參數(shù),一個(gè)是函數(shù)運(yùn)行的作用域(this),另一個(gè)是參數(shù)數(shù)組。
 call()方法第一個(gè)參數(shù)與apply()方法相同,但傳遞給函數(shù)的參數(shù)必須列舉出來(lái)。 */
    function sum(num1, num2) {
        return screenX+num1 + num2;
    }
    document.writeln(screenX+" is screenX");
    document.writeln(sum.call(window, 10, 10)); //20+screenX
    document.writeln(sum.apply(window,[10,20])); //30+screenX

</script>


輸出結(jié)果:
-4 is screenX 16 26