[英]this operator in javascript
Suppose I have JavaScript code like 假设我有类似的JavaScript代码
myClass = function(){
function doSomething(){
alert(this); // this1
}
}
alert(this); //this2
What those two 'this' objects are refer for?? 这两个'这个'对象是指什么?
The this
value in the global execution context, refers to the global object, eg: 全局执行上下文中的
this
值指的是全局对象,例如:
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: 对于函数代码,它实际上取决于您如何调用该函数,例如,在
this
情况下隐式设置this
值:
Calling a function with no base object reference : 调用没有基础对象引用的函数 :
myFunc();
The this
value will also refer to the global object. 在
this
值也将引用全局对象。
Calling a function bound as a property of an object : 调用绑定为对象属性的函数 :
obj.method();
The this
value will refer to obj
. this
值将引用obj
。
Using the new
operator : 使用
new
运算符 :
new MyFunc();
The this
value will refer to a newly created object that inherits from MyFunc.prototype
. this
值将引用从MyFunc.prototype
继承的新创建的对象。
Also, you can set explicitly that value when you invoke a function, using either the call
or apply
methods, for example: 此外,您可以使用
call
或apply
方法在call
函数时显式设置该值,例如:
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, eg: call
和apply
之间的区别在于,使用apply
,你可以使用Array或arguments
对象正确传递任意数量的参数,例如:
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. 如果
call
或apply
的第一个参数值为null
或undefined
,则this
值将引用全局对象。
(note that this will change in the future, with ECMAScript 5, where call
and apply
pass the thisArg
value without modification) (请注意,将来会改变,使用ECMAScript 5,其中
call
和apply
传递thisArg
值而不进行修改)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.