admin 管理员组文章数量: 1086019
Suppose I have JavaScript code like
myClass = function(){
function doSomething(){
alert(this); // this1
}
}
alert(this); //this2
What those two 'this' objects are refer for??
Suppose I have JavaScript code like
myClass = function(){
function doSomething(){
alert(this); // this1
}
}
alert(this); //this2
What those two 'this' objects are refer for??
Share Improve this question edited Jul 23, 2010 at 17:18 Teja Kantamneni 17.5k12 gold badges57 silver badges86 bronze badges asked Jul 23, 2010 at 17:16 MuhitMuhit 7871 gold badge7 silver badges17 bronze badges1 Answer
Reset to default 15The 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)
本文标签: this operator in javascriptStack Overflow
版权声明:本文标题:this operator in javascript - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.roclinux.cn/p/1744000455a2516350.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论