【问题标题】:Why "this" inside of a function's returning object window为什么在函数的返回对象窗口中出现“this”
【发布时间】:2014-04-08 15:55:31
【问题描述】:
在 javascript 中有两种类型的范围命名
功能范围
全局范围
现在我正在执行这段代码
function abc()
{
alert(this);
}
abc();
abc 调用返回我 [object Window]
为什么??函数创建了另一个范围,所以为什么它代表窗口
【问题讨论】:
标签:
javascript
function
this
【解决方案1】:
this,在任何函数内部,都是调用函数的对象。在您的情况下,您没有在任何对象上调用它。因此,默认情况下this 引用global 对象,在您的浏览器中,它是window 对象。
但是在strict 模式下,如果你这样调用它,this 将是undefined。
"use strict";
function abc() {
console.log(this); // undefined
}
abc();
或者
function abc() {
"use strict";
console.log(this); // undefined
}
abc();
【解决方案2】:
你的函数在 global(window) 对象下。我的意思是,
function abc()
{
alert(this);
}
abc();
// or You can either call by
window.abc()
你可以在自定义对象下编写你的函数
// Function under custom object
var customObj = {
abc : function () {
alert(this);
}
};
customObj.abc()