Original: rollbar.com/blog/top-10...
statement: slightly modified the original text, easy to read
Foreword
After reading thousands of projects, we found the 10 most common JavaScript errors. We'll tell you what causes these errors and how to prevent these errors. If you can avoid falling into the "trap", you will become a better developer.
JavaScript common mistakes Top 10:
For ease of reading, we will describe each error are reduced. Next, let's dig into every error, to determine what causes it, and how to avoid creating it.
1、Uncaught TypeError: Cannot read property
If you're a JavaScript developer, you might see the number of errors than you dare admit -. When you read an undefined object properties or call its methods, the error will appear in Chrome. You can easily test in the Chrome Developer Console.
For improper initialization state when this happens for many reasons, but the common one is rendering UI components.
Let's look at an example of a place in a real application: We chose React, but this situation also applies to Angular, Vue or any other framework.
class Quiz extends Component {
componentWillMount() {
axios.get('/thedata').then(res => {
this.setState({items: res.data});
});
}
render() {
return (
<ul>
{this.state.items.map(item =>
<li key={item.id}>{item.name}</li>
)}
</ul>
);
}
}
复制代码
Two important processes:
- State (e.g. this.state) begins assembly undefined.
- When the asynchronous data acquisition, whether it is in the constructor
componentWillMount
orcomponentDidMount
acquired, before the data is loaded components will appear at least once, whenQuiz
for the first time presented,this.state.items
is undefined.
It is easy to solve. The easiest way: initialization state in the constructor.
class Quiz extends Component {
// Added this:
constructor(props) {
super(props);
// Assign state itself, and a default value for items
this.state = {
items: []
};
}
componentWillMount() {
axios.get('/thedata').then(res => {
this.setState({items: res.data});
});
}
render() {
return (
<ul>
{this.state.items.map(item =>
<li key={item.id}>{item.name}</li>
)}
</ul>
);
}
}
复制代码
Specific code in your application may be different, but we hope we have given you enough clues to solve or avoid in your application to this problem. If not, keep reading, because we will cover more errors in the following example.
2、 TypeError: ‘undefined’ is not an object
This is an error when reading the undefined property or method on an object called Safari. You can easily test in the Safari Developer Console. This Chrome mentioned in the first point of error is basically the same, but Safari uses a different error message prompt.
3、 TypeError: null is not an object
This is an error occurred while reading the property or method on a null object called Safari. You can easily test in the Safari Developer Console.
Interestingly, in JavaScript, null
and undefined
it is different and that is why we see are two different error messages.
undefined
Typically variable has not been allocated, and null
indicates that the value is null. To verify that they are not equal, try using strict equality operator===
In our work, a scene such errors may occur is: If you try to use the element before loading element in JavaScript. Because the DOM API returns a null value for the blank object reference.
Any execution and handling of DOM elements JS code should be executed after the DOM element is created.
JS code as specified in HTML interpretation from top to bottom. So, if there is a label before DOM element, JS code inside the script tag will be executed when the browser parses the HTML page. If you have not created DOM elements before loading the script, this error can occur.
In this example, we can solve this problem by adding an event listener, the listener will be ready in time to inform us page. Once addEventListener
triggered, init()
the method can be used DOM elements.
<script>
function init() {
var myButton = document.getElementById("myButton");
var myTextfield = document.getElementById("myTextfield");
myButton.onclick = function() {
var userName = myTextfield.value;
}
}
document.addEventListener('readystatechange', function() {
if (document.readyState === "complete") {
init();
}
});
</script>
<form>
<input type="text" id="myTextfield" placeholder="Type your name" />
<input type="button" id="myButton" value="Go" />
</form>
复制代码
4、 (unknown): Script error
When the JavaScript error uncaught (caused by window.onerror handler error, rather than caught in the try-catch) when the browser cross-domain policy restrictions, will produce this kind of script error. For example, if you set your JavaScript code hosted on CDN, then any uncaught error will be reported as "script error" rather than a stack that contains useful information. This is a browser security measures designed to prevent cross-domain data transfer, otherwise it will not be allowed to communicate.
To get the real error message, do the following:
1. Set 'Access-Control-Allow-Origin' header
The Access-Control-Allow-Origin header to * indicates correctly access resources from any domain.
In Nginx set as follows:
Adding to the position instruction block add_header JavaScript file provided:
location ~ ^/assets/ {
add_header Access-Control-Allow-Origin *;
}
复制代码
2. <script>
Setcrossorigin="anonymous"
In your HTML code that you set up for Access-Control-Allow-Origin
each script, the script
settings on the label crossorigin =“anonymous”
. Add a script tag crossorigin
before the property, be sure to verify the above header
correctly sent.
In Firefox, if crossorigin property exists, but Access-Control-Allow-Origin header does not exist, the script will not be executed.
5、 TypeError: Object doesn’t support property
This is your mistake occurred in IE when calling undefined method. You can test in IE Developer Console.
This is equivalent to Chrome in “TypeError:”undefined“ is not a function”
error.
Yes, for the same logical errors, different browsers may have different error messages.
For Web applications using JavaScript namespace, which is a common problem IE browser. In this case, 99.9% of the reason is that IE can not bind method in the current namespace to this keyword.
For example: if you have a namespace in JS Rollbar
and methods isAwesome
. In general, if you are Rollbar
within a namespace, you can use the following syntax to invoke the isAwesome
method:
this.isAwesome();
复制代码
Chrome, Firefox and Opera would be happy with this syntax. But IE does not. Therefore, when using the JS namespace safest option is always to actual namespace as prefix.
Rollbar.isAwesome();
复制代码
6、 TypeError: ‘undefined’ is not a function
When you call an undefined function, which is generated in the wrong Chrome. You can test in Chrome and Mozilla Firefox Developer Console Developer Console.
function clearBoard(){
alert("Cleared");
}
document.addEventListener("click", function(){
this.clearBoard(); // what is “this” ?
});
复制代码
The implementation of the above code results in the following error:
“Uncaught TypeError:this.clearBoard is not a function”。
The reason should be clear that the implementation does not understand the context of pointing to the wrong cause.
7、 Uncaught RangeError
You call a recursive function will not terminate such errors occur. You can test in Chrome Developer Console.
Also, if you pass a value to function beyond the scope of this situation may also occur.
Many functions accept only a specific range of the input digital value. E.g:
toExponential(digits)
AndtoFixed(digits)
receiving 0-100toPrecision(digits)
Accepted 1-100
var num = 2.555555;
console.log(num.toExponential(4)); //OK
console.log(num.toExponential(-2)); //range error!
console.log(num.toFixed(2)); //OK
console.log(num.toFixed(105)); //range error!
console.log(num.toPrecision(1)); //OK
console.log(num.toPrecision(0)); //range error!
复制代码
8、 TypeError: Cannot read property ‘length’
This is an error in Chrome, because the read length of the property is undefined variables. You can test in Chrome Developer Console.
You will usually find the length defined in the array, but the array is not initialized or if the variable in another context, you may experience this error. Let's use the following example to understand this error.
var testArray = ["Test"];
function testFunction(testArray) {
for (var i = 0; i < testArray.length; i++) {
console.log(testArray[i]);
}
}
testFunction();
复制代码
The implementation of the code above will get an error:
Cannot read property 'length' of undefined
There are two ways to solve this problem:
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[i]);
}
}
testFunction();
复制代码
or
var testArray = ["Test"];
function testFunction(testArray) {
for (var i = 0; i < testArray.length; i++) {
console.log(testArray[i]);
}
}
testFunction(testArray);
复制代码
9、 Uncaught TypeError: Cannot set property
When we tried to access an undefined variable, it always returns undefined, we can not get or set any undefined attributes. In such a case would be thrown "Uncaught TypeError: Can not set property".
10. ReferenceError: event is not defined
When you try to access an undefined variable or variables beyond the current scope, this will lead to error. You can test in Chrome browser.
If you encounter this error when using the event, be sure to use the event object passed in as a parameter. Like old IE browser provides a global variable event, but not all browsers support.
document.addEventListener("mousemove", function (event) {
console.log(event);
})
复制代码
to sum up
We saw above the 10 most common mistakes, in fact, the knowledge involved is not difficult. When you carefully read "You do not know JavaScript" on the volume, these basic mistakes will not happen again.
In the final analysis is not solid grasp of the basics of JavaScript.
Related Articles Vue output plan
A friend recently asked me always Vue-related problems, so then I will output 10 Vue related articles, we hope to have some help. I'll keep updating one in 7-10 days.
- Vuex Vue injection process life cycle (complete)
- Learn the necessary knowledge base Vue source (complete)
- On Vue Responsive principle (complete)
- New and old VNode the process of patch
- How to develop functional components and upload npm
- From optimizing your Vue project areas
- Vue-Router speak from the front end design development route
- How to properly use Webpack in the project
- Vue rendering server
- How to choose the Axios and Fetch
I suggest that you focus on the public number, the first time you can receive the latest articles.
If you want to increase the exchange group, you can scan the code automatically pulled into the group:
Reproduced in: https: //juejin.im/post/5d0b9338f265da1bb80c34fd