Create an object
Java code
Copy codeThe Code is as follows:
<Script type = "text/javaScript">
Var newObject = new Object ();
// Create an object
NewObject. firstName = "frank ";
// Add a firstName attribute
NewObject. sayName = function (){
Alert (this. firstName );
}
// Add a sayName Method
// Call the sayName Method
// NewObject. sayName ();
// NewObject ["sayName"] ();
Var FirstName = newObject ["firstName"];
Var whatFunction;
// If (whatVolume = 1 ){
// WhatFunction = "sayName ";
//} Else if (whatVolume = 2 ){
// WhatFunction = "sayLoudly"
//}
// NewObject [whatFunction] ();
Function sayLoudly (){
Alert (this. firstName. toUpperCase ());
}
NewObject. sayLoudly = sayLoudly;
// Add method in another way
NewObject ["sayLoudly"] ();
</Script>
Using json (javaScript Object Notation) to create an Object has the same effect as above.
Java code
Copy codeThe Code is as follows:
Function sayLoudly (){
Alert (this. firstName. toUpperCase ());
}
Var newObject = {
FirstName: "frank ",
SayName: function () {alert (this. firstName );},
SayLoudly: sayLoudly
};
// You can also
Var newObject = {
FirstName: "frank ",
SayName: function () {alert (this. firstName );},
SayLoudly: sayLoudly,
LastName :{
LastName: "ziggy ",
SayName: function () {alert (this. lastName );}
}
};
NewObject. lastName. sayName ();
This is OK.
Java code
Copy codeThe Code is as follows:
Function sayLoudly (){
Alert (this. name. toUpperCase ());
}
Function sayName (){
Alert (this. name );
}
Var newObject = {
Name: "frank ",
SayName: sayName,
SayLoudly: sayLoudly,
LastName :{
Name: "ziggy ",
SayName: sayName
}
};
NewObject. lastName. sayName ();
Classes in JavaScript, as well as constructor...
Java code
Copy codeThe Code is as follows:
Function newClass (){
Alert ("constructor ");
This. firstName = "frank ";
This. sayName = function () {alert (this. firstName );}
// Return this;
}
// Var nc = newClass ();
Var nc = new newClass ();
// Nc. firstName = "ziggy"; is OK
Nc. sayName ();
You can also construct classes in this way.
Java code
Copy codeThe Code is as follows:
Function newClass (){
This. firstName = "frank ";
}
NewClass. prototype. sayName = function (){
Alert (this. firstName );
}
Var nc = new newClass ();
Nc. firstName = "ziggy ";
Nc. sayName ();
Var nc2 = new newClass ();
Nc2.sayName ();
Generally, prototypes is used to add methods. Therefore, no matter how many instances are available, there is only one sayName method in the memory.