本帖最后由 moliu 于 2009-11-28 19:51:13 编辑

解决方案 »

  1.   

    还有一个有意思的例子,与大家分享:
    function abc() {
        var aArr = new Array('button_1', 'button_2', 'button_3');
        for (var i=0; i<3; i++) {
            with({i:i})//对象直接量用在这儿了,你能想到吗?
    {
                document.getElementById(aArr[i]).onclick= function(){
                    alert('当前你点击的是button_'+(i+1));
                }
            }
        }
    }
    abc();
      

  2.   

    Array是构造数组对象的方法。上面的用法,其实是自身调用。下面还有这样的例子(来自<<悟透JAVASCRIPT>>):
    function WhoAmI() //定义一个函数WhoAmI
    {
    alert("I'm " + this.name + " of " + typeof(this));
    };
    WhoAmI(); //此时是this 当前这段代码的全局对象,在浏览器中就是window 对象,其
    name 属性为空字符串。输出:I'm of object
    var BillGates = {name: "Bill Gates"};
    BillGates.WhoAmI = WhoAmI; //将函数WhoAmI 作为BillGates 的方法。
    BillGates.WhoAmI(); //此时的this 是BillGates。输出:I'm Bill Gates of object
    var SteveJobs = {name: "Steve Jobs"};
    SteveJobs.WhoAmI = WhoAmI; //将函数WhoAmI 作为SteveJobs 的方法。
    SteveJobs.WhoAmI(); //此时的this 是SteveJobs。输出:I'm Steve Jobs of object
    WhoAmI.call(BillGates); //直接将BillGates 作为this,调用WhoAmI。输出:I'm Bill Gates of object
    WhoAmI.call(SteveJobs); //直接将SteveJobs 作为this,调用WhoAmI。输出:I'm Steve Jobs of object
    BillGates.WhoAmI.call(SteveJobs); //将SteveJobs 作为this,却调用BillGates 的
    WhoAmI 方法。输出:I'm Steve Jobs of object
    SteveJobs.WhoAmI.call(BillGates); //将BillGates 作为this,却调用SteveJobs 的
    WhoAmI 方法。输出:I'm Bill Gates of object
    WhoAmI.WhoAmI = WhoAmI; //将WhoAmI 函数设置为自身的方法。
    WhoAmI.name = "WhoAmI";
    WhoAmI.WhoAmI(); //此时的this 是WhoAmI 函数自己。输出:I'm WhoAmI of function

    ({name: "nobody", WhoAmI: WhoAmI}).WhoAmI(); //临时创建一个匿名对象并
    设置属性后调用WhoAmI 方法。输出:I'm nobody of object