js中this的应用场景

来源:互联网 发布:荣格心理学 知乎 编辑:程序博客网 时间:2024/06/17 19:32

this存在于函数中,函数的调用方式决定了this指代的对象

1:作为对象的方法用

var obj = {}; 

obj.x = 100; 
obj.y = function(){ alert( this.x ); }; 

obj.y(); //弹出 100 

2:作为函数调用

var x = "The Window";

function  f(){

    return this.x;//this指代全局对象window

}

f();//"The Window"

3:作为闭包函数调用

var x = "The Window";

function f1(){

    var x =  "My Object";

    return function(){

       return this.x;//this指代全局对象window,返回"The Window"

    }

}

4:apply或者call方法调用

var x = 0;

function f(){

return this.x;

}

var o = {};

o.x = 1;

f.call(o);//1

5:

function fn(num) {
    console.log( "fn: " + num );
    // count用于记录fn的被调用次数
    this.count++;
}
fn.count = 0;
var i;
for (i=0; i<10; i++) {
    if (i > 5) {
        fn( i );
    }
}
// fn: 6
// fn: 7
// fn: 8
// fn: 9

console.log( fn.count ); // 0 -- 耶?咋不是4捏?


0 0
原创粉丝点击