当我运行此代码时:
var Test = function() {
return this.stuff;
};
Test.stuff = 'Neat!';
document.write(Test() || 'Not neat.');
为什么会显示“不整洁”?为什么我不能使用
this.stuff
访问stuff属性? 最佳答案
尽管其他人已经发布了发生这种情况的原因(对this
的理解是不正确的),但这是一种可以可靠工作的解决方案。
更新:正如Raynos指出的那样,ECMAScript 5th Edition中的when using strict mode functions无效,不能使用arguments.callee
(它将引发TypeError)。因此,如果使用此方法,应格外小心。 (当使用[正确的] ECMAScript 5th Edition引擎时,没有理由在绑定(bind)到新作用域的函数的名称上使用arguments.callee
-请参见答案的结尾。)
var Test = function() {
// arguments.callee is the current function, if any
return arguments.callee.stuff
}
Test.stuff = 'Neat!'
alert(Test() || 'Not neat.') // Neat!
另一个是使用闭包:
var Test = (function () {
function fn () {
// closure over fn, which names this function-object
return fn.stuff
}
fn.stuff = 'Neat!' // here
return fn // do not combine with function declaration!
})()
Test.stuff = 'Neat!' // or here
alert(Test() || 'Not neat.') // Neat!
或者,直接关闭变量:
var Test = (function () {
var stuff = 'Neat!'
return function () {
// variable closure, no property
return stuff
}
})()
alert(Test() || 'Not neat.') // Neat!
或者...很多方式。
快乐的编码。
Aadit M Shah指出的另一种方法是使用函数标识符来引用当前函数:
var Test = function Temp () {
return Temp.stuff
}
Test.stuff = 'Neat!'
alert(Test() || 'Not neat.') // Neat! (But see below.)
正如Aadit指出的那样,根据ECMAScript 5th edition specification(第99页),这是有效的:
但是,某些浏览器(至少是IE9)错误地实现了此功能(并且我不确定上述行为在第三版中是否定义明确)。考虑:
var x = function y () { return y }; y = 42; x();
在IE9中将产生42,在FF8中将产生功能对象。 IE9在这里是不正确的,因为它在封闭范围内引入了
y
作为变量,ECMAScript禁止函数表达式使用该变量。这是一个有关此错误实现如何导致不同结果的上下文示例:var Test = function Temp () {
return Temp.stuff
}
Test.stuff = "Neat!"
Temp = {}
alert(Test() || 'Not neat.') // 'Not neat.' in IE9, 'Neat!' in FF8
关于javascript - “this”指的是其他东西吗?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/8102356/