Due to the flexibility of JavaScript, everyone can write code according to their own habits. There are functional programming methods and there are also a wider range of object literals used now. Due to the emergence of object-oriented, the function programming in JavaScript has gradually begun. Evolved into a class programming method. Now I will give a brief explanation of several more familiar programming habits:
1. Object literal:
var person = {
name:null,
setName:function(name){
this.name = name;
return this.name;
},
getName:function(){
alert(this.name);
}
}
A programming method with JavaScript features, contains attribute name, method setName and getName in the unit of class. Calling the method is simpler person.setname('R'), this all points to person, and the properties and methods of person are both It is not private and can be called.
2. Prototype constructor call mode
var Person = function(){
this.name = null;
}
Person.prototype.setName = function(name){
this.name = name;
}
Person.prototype.getName = function(){
alert(this.name);
}
It is also a very common programming method. Create a Person class, then use prototype to extend the class and add methods. The biggest difference from object literals is that when calling the method of this class, you must first new (similar to Java calling class). var p = new Person();p.getName(); If you create it directly without new, an error will be generated. Moreover, this error will not report an error and is difficult to detect. The reason for the error comes from this pointing to Person.prototype, and Person does not have a setName method.
3. Use anonymous functions to program functions
(function(){
var name;
var setName = function(n){
name = n;
}
window['person']['setName'] = setName;
var getName = function(){
alert(name);
}
window['person']['getName'] = getName;
})()
One of the biggest benefits of the emergence of classes is that it reduces the emergence of global variables, but if you are still accustomed to functional programming, it doesn't matter. Just create an anonymous function and perform closures, and you can program the function inside, and there is no need to Worry about the emergence of global variables. As seen above, var name cannot be called outside anonymous functions, and then use external variables to call internal functions or variables. You can use this to create private variables and private methods.