For some time did not write JS, review a bit of JS related things, the object-oriented part of the pick out to make a record. The following code synthesizes other blogs, but they are verified by themselves.
1, Factory mode
var Circle = function (){
varobj =NewObject ();
Obj. PI = 3.14;
Obj.area =function(r) {
return This. PI * R * r;
}
returnObj
}
varc =NewCircle ();
Alert (C.area (1.0));//result is 1
2, more formal notation (the way the constructor is)
functionCircle (R) {
This. R = r;
}
//Static Variables
Circle.pi = 3.14;
//Prototyping Methods
Circle.prototype.area =function(){
returnCircle.pi * This. R * This. R;
}
varc =NewCircle (3);
Console.log (C.area ()); // The result is 28.259999999999998
Summary: You do not need to recreate the object inside the function, but use this reference, and the function does not need a definite return
3,json notation
varCircle = {
"PI": 3.14,
"Area":function(r) {
return This. PI * R * r;
}
};
Console.log (Circle.area (2)); // The result is: 12.56
A small example of a third way of writing
var show = {
BTN: $ ('. Div '),
Init:function(){
varthat = This;
Alert This);
This. Btn.click (function{
That.change ();
Alert This);
});
},
Change:function(){
This. BTN.CSS ({' Background ': ' Green '});
}
}
show.init (); // Note the point where this is a problem
4, in fact, is the same as the first substance.
varCircle =function(r) {
This. R = r;
}
Circle.pi = 3.14;
Circle.prototype = {
Area:function(){
return This. R * This. R * CIRCLE.PI;
}
}
varobj =NewCircle (4);
Console.log (Obj.area ()); // The result is: 50.24
5, the last one
varCircle =NewFunction ("this. PI = 3.14;this.area = function (r) {return r*r*this. PI;} ");
obj =NewCircle ();
Console.log (Obj.area (4)); // The result is: 50.24
Summary: Individuals do not recommend this kind of writing, some confusion.
I personally prefer the following:
functionCircle (R) {
This. R = r;
}
//Static Variables
Circle.pi = 3.14;
//Prototyping Methods
Circle.prototype.area =function(){
return This. R * This. R * CIRCLE.PI;
}
varobj =NewCircle (4);
Console.log (Obj.area ()); // The result is: 50.24
can see the same result, feel this style more in line with my habits, of course, JS is relatively free, as long as the grammar is not wrong, you can choose any one and your favorite way to achieve their desired effect.
Several writing methods of JS object-oriented