The JavaScript language is a dynamic type of language, object-based and event-driven. In terms of object-oriented thinking, it also has the concept of class. JavaScript does not have a class keyword and is implemented using function.
1. Implementation mode and variable/method access domain control
1 |
functionfruit(name, color) |
Use this to identify a variable or method that is public. Xingcheng Fayon Gift
1 |
varapple = newfruit(‘apple‘, ‘red‘); |
Like most other languages, you instantiate an object of a class with the new keyword. So the Apple.name value is ' apple '. Internal variables use the var keyword:
3 |
varsubject = "welcome to nowamagic.net"; |
This time visit b1.subject, get the result is "undefined".
2. Extension of the class
JavaScript is a dynamic language, so we can add a property (field) or method to it after the class is created. The practice is to use prototype:
01 |
functionfruit(name, color) |
07 |
varapple = newfruit(‘apple‘, ‘red‘); |
08 |
varorange = newfruit(‘orange‘, ‘yellow‘); |
09 |
//apple.gender = ‘undefined‘ |
10 |
fruit.prototype.gender=1; |
13 |
//fruit.prototype.gender = 1 |
You can see the variable apple, Orange has the gender attribute, and the value is 1.
Others refer to the prototype extension as static methods or properties, which I think is inappropriate because static content cannot be accessed through objects, and here it is, and if you change Apple.gender, the value of Orange.gender is not affected. Another reason for this is that gender can not be used as a static property in other languages to access the class name directly:
1 |
apple.gender = 1 //error : student.gender undefined |
This is the only way:
1 |
fruit.prototype.gender // 值为 1 |
3. Relationship of objects to arrays
3 |
tom[‘Email‘]=‘[email protected]‘; |
4 |
// tom.Email 值为 ‘[email protected]‘ |
5 |
tom.Website="www.nowamagic.net"; |
6 |
// tom["Website"] 值为 "www.nowamagic.net" |
From this you can see that the field of the object can be accessed by an array, and vice versa. Accessed using field, style is more like object-oriented style, but it is convenient to use array azimuth in some traversal objects.
Briefly describe the classes and objects of JavaScript