Because of the flexibility of JavaScript, you can allow everyone to write code according to their own habits. There are functional programming methods, and there are now more extensive object literals. Due to the appearance of object-oriented, JavaScript's first functional programming has evolved into a class-style programming approach. Now I have a simple description of several familiar programming habits:
1. Object literal Volume:
var person = {
Name:null,
Setname:function (name) {
THIS.name = name;
return this.name;
},
Getname:function () {
alert (this.name);
}
}
A programming method with JavaScript characteristics that contains attribute name in class, methods SetName and GetName. The method is simpler to invoke Person.setname (' R '), this ends up pointing to person, A person's properties and methods are not private and can be invoked.
2.prototype Constructor Call pattern
var person = function () {
THIS.name = null;
}
Person.prototype.setName = function (name) {
THIS.name = name;
}
Person.prototype.getName = function () {
alert (this.name);
}
It's also a very common way of programming, creating a person class, and then using prototype to extend the class, adding methods. The biggest difference with object literals is that when you invoke the class's methods, you must first be new (similar to the Java calling Class). var p = new person (); P.getname (); If you do not use new, and create directly, you will generate an error. And this error will not be false, difficult to find. The reason for the error arises from this point to the Person.prototypel, and the person does not have the SetName method.
3. function programming using anonymous functions
(function () {
var name;
var setname = function (n) {
name = N;
}
window[' person ' [' setname '] = setname;
var getName = function () {
alert (name);
}
window[' person ' [' getName '] = getName;
})()
Class, one of the biggest benefits is the reduction of the global variable's appearance, but if you're still used to functional programming, it doesn't matter, as long as you create an anonymous function to do a closure, you can do functional programming inside, and you don't have to worry about global variables. The var name as seen above; Cannot be invoked outside of an anonymous function, and then uses external variables to invoke internal functions, or variables. You can use this to create private variables and private methods.