Summary of several confusing concepts in javascript

  • 2020-05-27 04:26:29
  • OfStack


var name = "The Window";
var object = {
name : "My Object",
getName: function(){

The getName() method here simply returns the value of Here are a few that call object.getName ()
The means and the results.
object.getName(); //"My Object"
(object.getName)(); //"My Object"
(object. getName = object. getName) (); //"The Window", in non-strict mode

In the third case (object.getName = object.getName); var fn=(object.getName = object.getName); fn ();


function outputNumbers(count){
for (var i=0; i < count; i++){
var i; // Redeclare variables 
alert(i); // count 


JavaScript never tells you whether the same variable has been declared multiple times; In this case, it simply ignores subsequent statements
See (however, it does the variable initialization in the subsequent declaration). Anonymous functions can be used to mimic block-level scopes and avoid this problem.


// Here is the block-level scope 
}(); // Error! 

This code causes syntax errors because JavaScript USES the function keyword as the beginning of a function declaration
Number declarations cannot be followed by parentheses. However, the function expression can be followed by parentheses. To convert a function declaration into a function expression,
You just add 1 to it like this.

// Here is the block-level scope 


function outputNumbers(count){
(function () {
for (var i=0; i < count; i++){
alert(i); // Lead to 1 A mistake! 

In this rewritten outputNumbers() function, we insert a private scope outside the for loop. The anonymous
Any variables defined in the function are destroyed at the end of execution. Therefore, the variable i can only be used in a loop and is destroyed as soon as it is used.
In a private scope, the variable count can be accessed because the anonymous function is a closure that can access the containing scope
All the variables.

This technique is often used outside functions in the global scope, limiting the number of variables and functions that can be added to the global scope.
In general, we should all add as few variables and functions to the global scope as possible. In a large scale with many developers working together
Too many global variables and functions in an application can easily lead to naming conflicts. By creating a private scope, every developer can
To use your own variables without worrying about messing up the global scope. Such as:

var now = new Date();
if (now.getMonth() == 0 && now.getDate() == 1){
alert("Happy new year!");

By placing the above code in a global scope, you can determine which day is January 1; So if we get to that day, we're going to use it
The household displays a message congratulating the New Year. Where the variable now is now a local variable in an anonymous function, we do not have to be in a global scope
Create it in.

That's all for this article, I hope you enjoy it.

Related articles: