Due to the flexibility of JavaScript, everyone can write code according to their own habits. There are functional programming methods, and there are also object literals that are widely used today. Due to the emergence of object-oriented, the functional programming that JavaScript just started has also gradually Evolved into class programming. Now I will briefly explain several 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 characteristics. It contains the attribute name, methods setName and getName in class units. It is relatively simple to call the method person.setname('R'). From this point onwards, this points to person, and the attributes and methods of person are all Not private, can be called.
2.Prototype constructor calling 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 to create a Person class, and then use prototype to extend the class and add methods. The biggest difference from object literals is that when calling methods of this class, you must first use new (similar to Java calling classes). var p = new Person();p.getName(); If you create it directly without using new, an error will occur. And this error will not be reported and is difficult to find. The reason for the error comes from this pointing to Person.prototypel, and Person does not have a setName method.
3. Use anonymous functions for functional programming
(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 occurrence of global variables. But if you are still used to functional programming, it doesn’t matter. As long as you create an anonymous function and perform closure, you can perform functional programming in it. No need to Worry about the appearance of global variables. As you can see above, the var name cannot be called outside the anonymous function. Then use external variables to call internal functions or variables. You can use this to create private variables and private methods.