1. Constructor method
A class is a template of an object that defines the method property data common to the object, and in JavaScript a function is an object, and it can be seen as a constructor of a class.
So we can define the class as follows:
// 1. Classical method of construction q=function(name) { this. name=name; this. func_a=function(ARG) { alert (arg); }; }; Q=new q (' Akun ');
2. Defining classes through prototypes
Prototypes (prototype) are a bit like a Python dictionary, where prototypes record the methods, properties, and templates of objects created from it.
Q.prototype={Age :- say_age:function() { alert (' age is ' + this. age); } }
Thus, Q produces objects that have not only the FUNC_A function but also the age property and the Say_age method.
q[' sex ']= ' male '; // The sex belongs to Q but instance of q! q=New Q (' Akun '); Q.say_age (); // Age is Q.func_a (' My name is ' + ' + q.name)//My name is Akun q.func_a (' The sex is ' + q.sex); the q.sex is undefined q.func_a (' The sex is ' + q.sex); The sex is male // If you change q[' sex '] to q.prototype[' sex ') then Q's instance Q has the sex attribute
3. "Minimalism"
var q={ init:function(name) { var obj={}; Obj.name=name; Obj.say_hello=function() { alert (this. Name); }; return obj; }, }; Q=q.init (' Akun '); Q.say_hello ();
The above uses the Init method to create an object, which is equivalent to Init as a construction method to return an object, and we define properties and methods on that object.
4. About this
q.fn=Q.prototype; Q.extend=function(Attr,value) { This[Attr]=value;};//This means QQ.fn.extend= Q.extend;//This in q.fn.extend points to Q.fn that is Q.prototypeQ.extend (' weight ', ' 100kg '); Q.fn.extend (' Myweight ', ' 99kg '); Q=NewQ (' Akun ') alert (q.weight)//undefinedAlert (q.myweight)//99kgAlert (q.weight)//100kg
A summary of the methods of JavaScript definition classes