这个错误跟chrome的"TypeError: ‘undefined’ is not a function"一样。只是不同的浏览器会报不同的错误语而已。
这种错误一般高发在使用命名空间的IE上。99.9%是因为IE无法解析this所指向的正确的命名空间。比如:
var Person = { name : "daisy", getName : function() { console.log(this.name) }, print: function() { this.getName() } };
比如在Person的命名空间里,print里可以去调用this.getName()这个方法。但是在IE不行,所以得明确的写明命名空间。
var Person = { name : "daisy", getName : function() { console.log(Person.name) }, print: function() { Person.getName() } };
(注:由于我手头没有window电脑,也懒得去找 = =,所以没有验证过,按照原文的翻译我理解是这个意思,大家有兴趣可以验证一下,评论区告诉我结论~)
六、TypeError: ‘undefined’ is not a function
这个就是上面说的原因,Chrome/火狐 调用了没有定义的方法导致。不在赘述。
当然除了疏忽,没有人会去直接调用一个没有定义的方法,大多是因为在回调函数或者是必包中,对this的理解不够造成的。比如:
function clearBoard(){ alert("Cleared"); } document.addEventListener("click", function(){ this.clearBoard(); // what is “this” ? });
在这个case中,回调函数里的this其实指向的是document,而外层定义的clearBoard命名空间作用域在window中,所以就会报"Uncaught TypeError: this.clearBoard is not a function".的错误。
有很多种方法可以解决上面的问题:
1、可以将外层的this存下来,这样self指向的还是windows。
var self=this; // save reference to 'this', while it's still this! document.addEventListener("click", function(){ self.clearBoard(); });
2、也可以用bind改变this的指向。
document.addEventListener("click",this.clearBoard.bind(this));
七、 Uncaught RangeError
这个错误会在Chrome的很多场景下出现。其中有一种就是使用了递归却没有使用停止的条件。
什么时候容易出这个错呢?在事件的回调中,如果要使用event要注意传入event。
document.addEventListener("mousemove", function (event) { console.log(event); })
因为有些浏览器不会自动帮你传,比如火狐,就会报错。所以最好还是自己传。
推荐教程:《JS教程》
以上就是JS 中排名前十的报错如何避免的详细内容,更多请关注 第一PHP社区 其它相关文章!