这个运算符在javascript中 [英] this operator in javascript
问题描述
假设我有JavaScript代码,如
Suppose I have JavaScript code like
myClass = function(){
function doSomething(){
alert(this); // this1
}
}
alert(this); //this2
这两个'this'对象是指什么?
What those two 'this' objects are refer for??
推荐答案
全局执行上下文中的 this
值是指全局对象,例如:
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.
调用绑定为对象属性的函数:
obj.method();
此
值将引用 obj
。
使用 new
运算符:
Using the new
operator:
new MyFunc();
此
值将引用一个新的创建的对象继承自 MyFunc.prototype
。
The this
value will refer to a newly created object that inherits from MyFunc.prototype
.
此外,您可以在调用函数时显式设置该值,使用 致电
或 apply
方法,例如:
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!"
调用
和<$ c之间的差异$ c> apply 是 apply
,你可以使用数组或参数正确传递任意数量的参数
对象,例如:
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
如果第一个参数值调用
或 apply
是 null
或 undefined
,此
值将引用全局对象。
If the first argument value of call
or apply
is null
or undefined
, the this
value will refer to the global object.
(请注意,这将在未来发生变化, ECMAScript 5,其中调用
和应用
传递 thisArg
值无需修改)
(note that this will change in the future, with ECMAScript 5, where call
and apply
pass the thisArg
value without modification)
这篇关于这个运算符在javascript中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!