现在的位置: 首页 > 综合 > 正文

JS中两个重要的方法 call & apply 学习

2012年09月11日 ⁄ 综合 ⁄ 共 941字 ⁄ 字号 评论关闭

JS一直不是很好! 以前看别人的代码有call和apply一直不知道是什么意思!今天学习了!更多资料来源于网络!感谢各位无私的人!

正题:

Function.prototpe.apply(instance,args)  //args 数组

Function.prototpe.Call(instance,a1,a2)  //a1,a2 单个参数

        /**
        *  People 
        */
        function People() {
            this.name = 'jinho';
            this.showName = function() {
                if (arguments) { alert(this.name + "\r\narg:=:" + arguments.length); return; }
                alert(this.name);
            };
        }
        /*
        *  Student
        */
        function Student() {
            this.name = 'student';
        }
        var p= new People; //创建对象
        var s= new Student; //创建对象
        p.showName.call(s); //输出"'student'",说明showName函数的当前this已经变为p了,神奇之处来了! s对象本来没有showName()方法啊! 可以他还是执行了! 是由于call函数把 s 作为了 this!

        p.showName.apply(s); //输出"'student'"
        //call函数和apply函数的区别是call 的语法是function.call(obj,param1,param2……);applay的语法是function.call(obj,[]/*params[]参数数组*/);

本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/jinho/archive/2010/03/11/5371933.aspx

抱歉!评论已关闭.