In view of its relatively weak JavaScript, I found a book to supplement it (known as the JavaScript authoritative guide of sharp books ). Although the content of the book is a little more, it fully shows that there are still a lot of things in js. Although our positioning is not a front-end, we 'd better understand the js technology that has been developing for nearly 20 years but is still very popular.
Two years ago, I wrote a blog about the JavaScript closure, so I was very impressed with the word closure. When I read this book, I saw the closure again. Now I will look at the closure again, what are their differences?
As we all know, there is no class concept in JavaScript, and there is no private or public member variable. But it does exist.
Take the following example:
Function MyClass () {this. name = 'lily'; var age = 2;} var test = new MyClass (); alert (test. name); // Li Si alert (test. age) // undefinedtest. name = 'zhang san ';
In the process of debugging with Google Chrome, the age value is always invisible, but it does exist. Although no error is reported when test. age is called, the value of age cannot be obtained. For name, it is modified using this., so it is equivalent to a public variable. The variable declared with var is private. As for the class (in Java), it is not a function.
So how should private variables be accessed?
In Java, we want to access private variables by providing them with the get and set methods. The same is true here. See the following code:
Function MyClass () {this. name = 'lily'; var age = 2; this. getAge = function () {alert (age);} this. setAge = function (value) {if (value> 0 & amp; value <150) age = value ;}}var test = new MyClass (); test. getAge () // 2test. setAge (11); test. getAge (); // 11
Here, this completely simulates the operations of public, private, and private attributes in a Java class.
The method of Private Attribute operations has a unique name in JavaScript: closure.
Through the Declaration of Java classes to understand JavaScript, we suddenly found that closures that were once considered hard to understand have become less familiar with why such a concept is defined.
Although no get and set methods for javascript attributes have been generated so far, ext has provided such a tool method to directly use get and set methods for javascript Object Attributes.
In the past javascript usage, we used process-oriented methods, which exposed the low degree of reuse of javascript code. Javascript object-oriented is imperative.