this in javascript

The this value in the global execution context, refers to the global object, e.g.:

this=== window;// true

For Function Code, it really depends on how do you invoke the function, for example, the this value is implicitly set when:

Calling a function with no base object reference:

myFunc();

The this value will also refer to the global object.

Calling a function bound as a property of an object:

obj.method();

The this value will refer to obj.

Using the new operator:

new MyFunc();

The this value will refer to a newly created object that inherits from MyFunc.prototype.

Also, you can set explicitly that value when you invoke a function, using either the call or apply methods, for example:

function test(arg){

  alert(this+ arg);

}

test.call("Hello"," world!");// will alert "Hello World!"

The difference between call and apply is that with apply, you can pass correctly any number of arguments, using an Array or an arguments object, e.g.:

function sum(){

var result =0;

for(var i =0; i < arguments.length; i++){

    result += arguments[i];

}

return result;

}

var args =[1,2,3,4];sum.apply(null, args);// 10

// equivalent to call

sum(1,2,3,4);// 10

If the first argument value of call or apply is null or undefined, the this value will refer to the global object.

(note that this will change in the future, with ECMAScript 5, where call and apply pass the thisArg value without modification)

转载于:https://www.cnblogs.com/Yjanuary/archive/2013/01/16/2863097.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值