js中this的应用场景

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捏?


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值