考虑这个代码片段: Javascript代码
[mw_shl_code=javascript,true]function testFunction() {
this.clearLocalStorage();
this.timer = setTimeout(function() {
this.clearBoard(); // what is "this"?
}, 0);
};[/mw_shl_code]
执行上面的代码会导致以下错误:“Uncaught TypeError:undefined is not a function”。 你得到上述错误的原因是,当你调用setTimeout()时,实际上是调用window.setTimeout()。 因此,在窗口对象的上下文中定义了一个传递给setTimeout()的匿名函数,该函数没有clearBoard()方法。
一个传统的,旧浏览器兼容的解决方案是简单地将您的 this 保存在一个变量,然后可以由闭包继承。 例如: Javascript代码
[mw_shl_code=javascript,true]function testFunction () {
this.clearLocalStorage();
var self = this; // save reference to 'this', while it's still this!
this.timer = setTimeout(function(){
self.clearBoard();
}, 0);
};[/mw_shl_code]
或者,在较新的浏览器中,可以使用bind()方法传递适当的引用: Javascript代码
[mw_shl_code=applescript,true]function testFunction () {
this.clearLocalStorage();
this.timer = setTimeout(this.reset.bind(this), 0); // bind to 'this'
};
function testFunction(){
this.clearBoard(); //back in the context of the right 'this'!
};[/mw_shl_code]
7. Uncaught RangeError: Maximum call stack
这是 Chrome 在一些情况下会发生的错误。 一个是当你调用一个不终止的递归函数。您可以在 Chrome 开发者控制台中进行测试。
此外,如果您将值传递给超出范围的函数,也可能会发生这种情况。 许多函数只接受其输入值的特定范围的数字。 例如:Number.toExponential(digits) 和 Number.toFixed(digits) 接受 0 到 20 的数字,Number.toPrecision(digits) 接受 1 到 21 的数字。 Javascript代码
[mw_shl_code=javascript,true]var a = new Array(4294967295); //OK
var b = new Array(-1); //range error
var num = 2.555555;
document.writeln(num.toExponential(4)); //OK
document.writeln(num.toExponential(-2)); //range error!
num = 2.9999;
document.writeln(num.toFixed(2)); //OK
document.writeln(num.toFixed(25)); //range error!
num = 2.3456;
document.writeln(num.toPrecision(1)); //OK
document.writeln(num.toPrecision(22)); //range error![/mw_shl_code]
8. TypeError: Cannot read property ‘length’
这是 Chrome 中发生的错误,因为读取未定义变量的长度属性。 您可以在 Chrome 开发者控制台中进行测试。
您通常会在数组中找到定义的长度,但是如果数组未初始化或者变量名称在另一个上下文中隐藏,则可能会遇到此错误。让我们用下面的例子来理解这个错误。 Javascript代码
[mw_shl_code=javascript,true]var testArray = ["Test"];
function testFunction(testArray) {
for (var i = 0; i < testArray.length; i++) {
console.log(testArray);
}
}
testFunction();[/mw_shl_code]
您有两种方法可以解决您的问题:
1. 删除函数声明语句中的参数(事实上你想访问那些声明在函数之外的变量,所以你不需要函数的参数): Javascript代码
[mw_shl_code=javascript,true]var testArray = ["Test"];
/* Precondition: defined testArray outside of a function */
function testFunction(/* No params */) {
for (var i = 0; i < testArray.length; i++) {
console.log(testArray);
}
}
testFunction();[/mw_shl_code]
2. 用声明的数组调用该函数: Javascript代码
[mw_shl_code=javascript,true]var testArray = ["Test"];
function testFunction(testArray) {
for (var i = 0; i < testArray.length; i++) {
console.log(testArray);
}
}
testFunction(testArray);[/mw_shl_code]
9. Uncaught TypeError: Cannot set property
当我们尝试访问一个未定义的变量时,它总是返回 undefined,我们不能获取或设置任何未定义的属性。 在这种情况下,应用程序将抛出 “Uncaught TypeError: Cannot set property”。
例如,在 Chrome 浏览器中:
如果测试对象不存在,错误将会抛出 “Uncaught TypeErrorUncaught TypeError: Cannot set property”。