JS built in a lot of classes, we use, are from these classes are instantiated.
1 function Object () {} 2 function Array () {} 3 function String () {} 4 function Boolean () {} 5 function Function () {}
For example, var a = {}; equals var a = new Object ();
var a =[]; equals var a = new Array ();
Now we're going to create a custom class. Write down the following code in Smartlist.js:
1+function(Flexx) {2' Use strict ';3 4 functionSmartList () {5 //constructor that executes the code here when the class is new6Console.log (' created a SmartList object ');7Console.log ( This);8 }9 TenFlexx.smartlist = SmartList;//assigns the class to the XX global object One A} (window.xx = window.xx | | {});
This is called in Main.js:
1 function () {2 ' use strict '; 3 4 var New xx. SmartList (); 5 Console.log (memberlist); 6 7 } ();
The results of the operation are as follows:
Here, we call XX with new. SmartList (), new makes the function a constructor, silently doing something for us, such as creating an object, pointing this to the object, and finally returning the object.
Let's look at the difference between the new call function and the direct call function.
1+function(Flexx) {2' Use strict ';3 4 functionSmartList () {5Console.log (' created a SmartList object ');6Console.log ( This);7 }8 9 varList1 =SmartList ();Ten varList2 =NewSmartList (); OneConsole.log (' List1 is ', list1); AConsole.log (' List2 is ', list2); - -Flexx.smartlist =SmartList; the -} (window.xx = window.xx | | {});
The results of the operation are as follows:
When you call a function with new, the This inside of the function points to the created object, and the function return value is also the object created. Return affects the return value of the directly called function, but does not affect the return value of the function called by new (this self-test).
We can give the object a list property at initialization time to save our list data.
After new, the Memberlist object has a list property.
Here's the prototype. For example, for this class, we create a prototype method called update, which I want to update the list's data with.
As you can see from the console, the prototype method is placed in a hidden __proto__ attribute. Looking at the proto on the root property of an object, the expanded display of opaque is the prototype method that this object inherits from the class, and all objects created from this class have this update method.
So I can refresh my list in the Update method.
You can see the list update for our incoming array.
The following creates a GetData method to get the list data on this object.
This is the most famous set and get method.
Finally, thank you for the explanation of the great God CX.
JS class, prototype--study notes