Java programmer's JavaScript learning notes (4 -- closure/getter/setter), gettersetter

Source: Internet
Author: User

Java programmer's JavaScript learning notes (4 -- closure/getter/setter), gettersetter

We plan to complete this note in the following order:

This is Part 1 of the note. Let's talk about closures/getter/setter and look at the variable scopes and encapsulation methods in JavaScript.

1. Closure

Closure is a simple and practical language feature of JavaScript. Closure:
It makes up for the absence of public/private access control operators in the function and protects the security of internal variables in the function.
So that when the function object is passed as a parameter, not only the operation logic, but also the relevant variables are passed.
So that different instances of the function "class" can enjoy their own properties.
Let's look at it one by one.

1.1. Protection of Private variables 1.1.1, Principles

The main feature of a closure is that when a function is returned as a return value, it is returned together with the environment when the function is defined (including the variables that can be accessed by the function outside the function, make sure that these variables are not destroyed because they are attached to the object.
What does it mean? See the following code:
// Code segment 1
Function UiObject (){
Var childCount = 0; // internal variable of the function,
Return 0;
}
 
Var funcReturnValue = UiObject (); // call the function and return 0
Console. log (UiObject. childCount); // output: undefined. The internal variables have been destroyed because the function call is complete.
 
ChildCount is destroyed after the call of the UiObject function ends. from another perspective, it protects the internal variables of the function.
On this basis, if we have a way to ensure that the internal variables of the function are not destroyed, and provide methods to access them, we can access the private variables through the public method.
The Code is as follows:
// Code segment 2
Function UiObject (){
Var childCount = 0; // internal variable of the Function
Function getChildCount (){
ChildCount = 6;
Return childCount;
}
Return getChildCount;
}
Var funcReturnFObject = UiObject (); // call the function and return the getChildCount function. The return value is a closure.
Console. log (funcReturnFObject (); // output: 6
Next, let's take a look at how to use this feature of the closure to protect private attributes.
 
 

1.1.2. Syntax

Based on code snippet 2, code snippet 3 provides multiple methods to access private attributes at the same time.
// Code segment 3
Function UiObject (){
Var childCount = 0; // internal variable of the Function

Return {
GetChildCount: function (){
Return childCount;
},
SetChildCount: function (cnt ){
ChildCount = cnt;
}
};
}
 
Var o = UiObject (); // call the function and return the getChildCount function. The return value is a closure.
O. setChildCount (6 );
Console. log (o. getChildCount (); // output: 6
 
Think: What if var childCount = 0; change to this. childCount = 0?
We have studied this before. The "this. childCount = 0;" statement is to append childCount as the caller's attribute. this. childCount will have the same lifecycle as the caller. This does not conflict with the closure.
 
Code segment 3 can also be written as code segment 4.
 
// Code segment 4
Function UiObject (){
Var childCount = 0; // internal variable of the Function
This. setChildCount = function (cnt ){
ChildCount = cnt;
};
This. getChildCount = function (){
Return childCount;
};
}
 
Var ui = new UiObject (); // call the function and return retObj
Console. log (ui. childCount); // output: undefined. The local variable has been destroyed because the function call is complete.
Ui. setChildCount (3); // due to the function of the closure, the ui still saves the variable childCount and operates on it.
Console. log (ui. getChildCount (); // output: 3
 
"This. setChildCount = function (cnt) {childCount = cnt ;};" is equivalent to defining a function in the UiObject and "passing" the function to the ui object. A closure is also generated.
 

1.2 When passing functions, the context is also transferred

Through the above example, we have seen this feature.
It can be used in specific application scenarios.

1.3. Dedicated variables for different instances

As we know, a closure is generated during the function transfer process. Are the closures produced by the same method the same, or are different copies created for each pass?
See the following code:
// Code segment 5
Function UiObject (){
Var childCount = 0; // internal variable of the Function

Return {
GetChildCount: function (){
Return childCount;
},
SetChildCount: function (cnt ){
ChildCount = cnt;
}
};
}
 
Var ui1 = UiObject ();
Var ui2 = UiObject ();
 
Ui1.setChildCount (1 );
Ui2.setChildCount (2 );
 
Console. log (ui1.getChildCount (); // output: 1
Console. log (ui2.getChildCount (); // output: 2
 
Each time a closure is generated, it is a different copy.
 
Thinking: Compare Java to deepen understanding.
 
 

2. getter/setter


JavaScript
// Code segment 6
Var uiPanel = {
_ Type: 'panel ',
_ Width:-1,
_ Height:-1,

Get type () {return this. _ type ;},

Get width () {return this. _ width ;},
Set width (v) {this. _ width = v ;},

Get height () {return this. _ height ;},
Set height (v) {this. _ height = v ;}
};
 
UiPanel. type = 'textfield '; // does not work
Console. log ('Type: '+ uiPanel. type); // ouput: type: Panel
 
UiPanel. width = 800 ;//
Console. log ('width: '+ uiPanel. width); // ouput: width: 800

In terms of syntax, there are more object-oriented models.
In addition to controlling the read and write permissions of attributes through the set/set keyword during definition. You can also dynamically add attributes through the Object. defineProperty () function at runtime, and provide more refined control.
The Code is as follows (the following code is not tested ):
Var o = {};
Object. defineProperty (o, 'propname ',{
Value: 1, // attribute value, which can also be set through the get: function () {retun x;} Method
Writeable: true, // whether the attribute value can be set through the o. propName = newValue; Method
Enumerable: false, // whether enumerable can be enumerated
Retriable: true // whether it can be configured through defineProperty
});
In addition, there are a series of APIs that can complete attribute configuration and detection. As follows:
Object. getOwnPropertyDescriptor {x: 1}, "x "}
Object. keys (obj); // obtain all the enumerated "instance attributes" of the Object"
Object. getOwnPropertyNames (obj); // obtain all "instance attributes" on the Object"
Obj. hasOwnProperty ('id'); // if the object obj has an attribute id, true is returned regardless of whether the id can be enumerated.


3. Summary

When most people are used to object-oriented thinking and methods, the language needs to be satisfied in terms of features, which is unreasonable and not beautiful. But the world is so imperfect.

JavsScript is brilliant and has to be transformed into a host a warrior. Who will be responsible for the future?

ECMAScript 5 is neither a revolutionary innovation nor a life-saving means. The world can be better.





What is the setter // getter () method in JAVA?

Use the code to explain:
Public class Student {
String name;

Public String getName (){
Return name;
}
Public void setName (String name ){
This. name = name;
}

/**
* @ Param args
*/
Public static void main (String [] args ){
// TODO Auto-generated method stub
Student s1 = new Student ();
S1.setName ("James ");
System. out. println ("Student name:" + s1.getName ());
}
}

The above indicates creating a student class, declaring a name variable, and giving it the getter and setter methods.
Let's first talk about the setter method. No value is assigned when the name variable is created at the beginning, and then we use this method to assign it "James"
Let's talk about the getter method. After the name variable has the value "James", you can use this method to call it out.

JAVA Programmers need to learn those courses

Think more, read more examples of old employees, observe some coding specifications, including writing and architecture specifications
Too much knowledge has been learned. javase (java core technology) jsp (jsp2.0 Technical Manual) servlet struts (struts in action) spring (spring Development Guide)
-----------------------------------------------
I am here to tell you what can be used at work. First of all, you need to know the basics of JavaSE. jsp should be written and understood. EL is better to write something. jstl is basically not needed because of Struts. Servlet requires more, because Struts is an advanced application of Jsp + Servlet. Then you can learn the framework. You can understand the structure of Struts. You need to know the running and loading processes, and have a number in your mind. Spring is the same. We generally don't need hibrnate because the project is too big to show its advantages, small. Practice code writing strictly follows the MVC specifications, and upper-layer methods or attributes are not allowed to be called at the lower layer. The reference books we read at the company are the ones I have mentioned. It is useful to know more about ajax. In fact, in my opinion, the primary knowledge is the knowledge of JavaSE, and the advanced ones are not high enough. Every company has its own specifications and Methods. If it is your turn to design, you can write it honestly. The design mode is used when you participate in design.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.