JavaScript creates objects in several ways:
1. Create an object using the object constructor.
// 1. Create an object using the object constructor, the following code creates a person object and prints the property value of name in two ways. function CreateObject () { varnew Object (); = "Kevin"; = +; alert (person.name); Alert (person["name"]); }
2. Create an object using the object literal.
// 2. Create an object using the object literal; do not be surprised person["5"], here is legal, in addition to the use of such parentheses between the fields can have spaces, such as person["my Age"]. function createObject2 () { var person = { "Kevin" , 5: "Test" ,True}; alert (person.name); Alert (person["5"]); Alert (person["My Sex"]); }
3. Create an object using prototype mode.
//3. Create an object using prototype mode. As you can see from the following code execution results, the value of the friends of the two instances is the same, which may not be what we expected. functionPerson () {} Person.prototype={constructor:person, Name:"Kevin", Age:31, Job:"SE", friends: ["Jams", "Martin"], Sayfriends:function() {alert ( This. Friends); } }; varPerson1 =NewPerson (); Person1.friends.push ("Joe"); Person1.sayfriends ();//Jams,martin,joe varPerson2 =NewPerson (); Person2.sayfriends ();//James,martin,joe
4. Use Factory mode to create objects, return person objects with properties and methods
function Createperson (name, age,job) { varnew Object (); O.name=name; O.age=31; O.sayname=function() { alert (this. Name); }; return o;} Createperson ("Kevin", +, "se"). Sayname ();
Recommended methods for creating objects
1. Combine to create objects using prototype mode and constructors. (This is the most widely used and most recognized method of creating objects)
functionStudent (name, age) { This. Name =name; This. Age =Age ; This. Friends = ["Tom", "Lily"]; } Student.prototype.sayFriends=function() {alert ( This. Friends); }; varSTU1 =NewStudent ("CK", 28); varSTU2 =NewStudent ("sh", 27); Stu1.friends.push ("Lucy"); Stu1.sayfriends (); //Tom,lily,lucyStu2.sayfriends ();//tom,lily
2, dynamic prototype mode. (the benefit of this pattern is that it looks more like traditional object-oriented programming, with better encapsulation)
functionStudent (name, age) {//Properties This. Name =name; This. Age =Age ; This. Friends = ["Jams", "Martin"]; //Method if(typeof This. sayname! = "function") {Student.prototype.sayName=function() {alert ( This. Name); }; Student.prototype.sayFriends=function() {alert ( This. Friends); }; } } varStu =NewStudent ("CK", 23); Stu.sayname ();
Several ways that JavaScript creates objects