srain
12/2/2014 - 5:20 AM

js中this指代的对象

js中this指代的对象

(function() {

    var data = {
        movePage: function() {
            this.arg = 1;
            this.dowhat = {
                method1: function() {
                    alert("1当前对象的arg属性值:" + this.arg);
                },
                method2: function() {
                    alert("2当前对象的arg属性值:" + this.arg);
                }
            };
        }
    };

    var test = new data.movePage();
    // 我们通常的调用函数的形式。alert的值为undefined
    test.dowhat.method1();
    // 改变this对象指代的当前上下文。
    // 也就是说:这句代码会执行method1方法,并且将this指代的当前上下文指到test对象,即movePage函数。
    // 而movePage函数中arg的值为1,那么alert后的值为1
    test.dowhat.method1.call(test);

})();