this对象

this对象

 

1.纯粹的函数调用

function test(){
        this.x = 1;
        alert(this.x);
    }
    test();//1

2.函数作为某个对象的方法进行调用,这是this就指向这个上级的对象。

复制代码
function test()
    {
        alert(this.x);
    }
    var o = {};
    o.x = 1;
    o.m = test;
    o.m();//1
复制代码

3.作为构造函数进行调用

function test(){
        this.x = 1;
    }
    var test1 = new test();
    alert(test1.x);//1

为了证明此时this不是指向全局变量

复制代码
var x = 2;
    function test(){
     this.x = 1;
    }
    var o = new test();
    alert(x);//2
复制代码

4.apply调用apply方法中第一个参数就是this指向的对象

复制代码
var x = 2;
    function test(){
        alert(this.x);
    }
    var o = {};
    o.x = 1;
    o.m = test;
    o.m.apply(o);
复制代码

 

--转发
posted @ 2016-11-14 22:49  W+7  阅读(142)  评论(0)    收藏  举报