什么是这个(内侧内功能)参照在下面的代码上下文?它是否指向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;
};
};
}
Run Code Online (Sandbox Code Playgroud)
谢谢
CMS*_*CMS 10
根据函数的调用方式隐式this设置该值,有三种情况会发生这种情况:
当调用没有基础对象或非引用的引用时:
myFn(); // the myFn reference has no base object
(function () {})(); // non-reference
Run Code Online (Sandbox Code Playgroud)
该this值将指向全局对象1
当引用包含基础对象时,例如:
myObj.method();
Run Code Online (Sandbox Code Playgroud)
this里面的值method将指向myObj.
使用new运营商时:
var obj = new Foo();
Run Code Online (Sandbox Code Playgroud)
该this内部值Foo函数,将指向一个新创建的对象,从继承Foo.prototype.
通过使用和方法,this也可以显式设置该值,例如:callapplycall
function test(a) {
return alert(this + a);
}
test.call("hello", " world"); // alerts "hello world"
Run Code Online (Sandbox Code Playgroud)
或者apply如果我们需要将一组参数从数组"应用"到函数中:
function test(a, b) {
return alert(this + a + b);
}
var args = ["my ", "world "];
test.apply("hello ", args); // alerts "hello my world"
Run Code Online (Sandbox Code Playgroud)
[1]这在新的 ECMAScript第5版严格模式上有所改变,现在当一个没有基础对象的函数引用或非引用被调用时(作为第一种情况),该this值将包含undefined.
这是因为在使用构造函数时,人们new在调用构造函数时经常忘记使用运算符.
当发生这种情况时,该this值指向全局对象,最终添加了不需要的全局属性.
现在在严格模式下,this将包含undefined,如果对它进行属性查找(this.foo = 'foo'),我们将有一个很好的TypeError异常,而不是具有全局foo属性.
| 归档时间: |
|
| 查看次数: |
400 次 |
| 最近记录: |