什么是“这个"?指 [英] What does "this" refer to
问题描述
在以下代码上下文中, this (内部函数内部)指的是什么?它指向TimeSpan吗?
what is the this (inside inner functions) referring to in the following code context? Does it point to TimeSpan?
var TimeSpan = function (days, hours, minutes, seconds, milliseconds) {
var attrs = "days hours minutes seconds milliseconds".split(/\s+/);
var gFn = function (attr) {
return function () {
return this[attr];
};
};
var sFn = function (attr) {
return function (val) {
this[attr] = val;
return this;
};
};
}
谢谢
推荐答案
this
值是隐式设置的,具体取决于函数的调用方式>,在三种情况下会发生这种情况:
The this
value is set implicitly depending on how the function is invoked, there are three cases where this happens:
-
当调用没有基础对象的引用或非引用时:
When a reference with no base-object, or a non-reference is invoked:
myFn(); // the myFn reference has no base object
(function () {})(); // non-reference
this
值将指向全局对象 1
The this
value will point to the global object 1
当引用包含基础对象时,例如:
When a reference contains a base object, for example:
myObj.method();
方法
中的 this
值将指向 myObj
.
使用 new
运算符时:
var obj = new Foo();
Foo
函数内的 this
值将指向一个新创建的对象,该对象继承自 Foo.prototype
.
The this
value inside the Foo
function, will point to a newly created object that inherits from Foo.prototype
.
也可以使用 应用
方法,例如,使用 call
:
function test(a) {
return alert(this + a);
}
test.call("hello", " world"); // alerts "hello world"
或者如果需要将一组参数从数组应用"到函数,则使用 apply
:
Or with apply
if we need to "apply" a set of arguments from an array to a function:
function test(a, b) {
return alert(this + a + b);
}
var args = ["my ", "world "];
test.apply("hello ", args); // alerts "hello my world"
[1] This has changed on the new ECMAScript 5th Strict Mode, now when a function reference with no base object, or a non-reference is invoked (as the first case), the this
value will contain undefined
.
之所以这样做,是因为在使用构造函数时,人们经常在调用构造函数时忘记使用 new
运算符.
This was made because when working with constructor functions, people often forgot to use the new
operator when calling the constructor.
发生这种情况时, this
值指向全局对象,最终添加了不需要的全局属性.
When that happened, the this
value pointed to the global object, and that ended up adding unwanted global properties.
现在在严格模式下, this
将包含未定义,并且如果对其进行属性查找( this.foo ='foo'
),我们将得到一个不错的 TypeError
异常,而不是具有全局 foo
属性.
Now on strict mode, this
will contain undefined, and if property lookup is made on it (this.foo = 'foo'
) we will have a nice TypeError
exception, instead of having a global foo
property.
这篇关于什么是“这个"?指的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!