How to create objects in javascript and create objects in javascript

Source: Internet
Author: User
Tags hasownproperty

How to create objects in javascript and create objects in javascript

JS is an object-based language. It can use object-oriented ideas to simulate object-oriented languages such as JAVA | C ++.
• Process-oriented
Follow the steps to solve the problem

• Object-oriented
The principal focuses on the objects (content and roles) required to solve the problem, and then calls related methods according to the business logic according to certain rules.

Objects can be divided into system objects and custom objects. You can call the system constructor to create system objects, such as array and date. Custom objects must be created by themselves and cannot be created by using system functions.

Create an object using javascript

1. directly create

// Create an Object directly // JS // 1: Create an empty Object var person1 = new Object (); // 2: add the attributes and methods required by this object to person1.name = "ailer"; console. log (person1.name); person1.gender = "male"; // 3: Method to add this object | (function) person1. manager = function () {console. log ("Ailer is my English name");} // 4: Call object method: object. method Name (); person1.manager (); // function | method? When a function belongs to an object, the function belongs to the method under this object. The function is called by the method name. // variable | attribute? When a variable belongs to an object, the variable is the method of the object. Call a variable using the attribute name. // Add person1.age = "6"; // change person1.name = "lemon"; // check the console. log (person1.name); // delete person1.age; console. log (person1.age) ;=> undefined // reference type, stores the address // basic type: stores the Value Flag/* var arr1 = [1, 2, 3, 4] var arr2 = [5, 6, 7, 9]; var arr2 = arr1; // arr2 [0] = 10; // change the value in arr2, arr1 also changes alert (arr1 [0]); // ===> 10 reference type */var per2 = new Object (); per2.name = "Relia "; per2.age = "18"; per2.gender = "femal"; per2.hober = "lemons"; // 1: Pass. (point syntax) Access attributes // 2: Access the attributes of an object through [] (square brackets; the square brackets must be an attribute string or a variable that saves the attribute string | the square brackets var n = "name" // console are used only when the attribute is traversed. log (per2 ["name"]); // double quotation mark console. log (per2 [n]); for (var property in per2) {// console. log (per2 [property]);}

Although intuitive, code redundancy occurs when multiple objects are created.

Ii. Create with function (factory Mode)

To solve the problem of multiple similar object declarations, we can use a method called the factory pattern to solve the problem of generating a large number of duplicates for the instantiated object.

// Define the constructor function createPerson (name, age) {// create a new empty Object var person = new Object; // Add attributes | method person. name = name; person. age = age; person. manager = function () {console. log ("ai") ;}// return person;} var per1 = createPerson ("ailer", 12); console. log (per1.name); var per2 = createPerson ("lemon", 23); console. log (per2.age); console. log (per2 instanceof Object); // true console. log (per2 instanceof createPerson); // false // cannot distinguish this object type console. log (per2.manager = per1.manager); // false, the space of per1 and per2 can be opened and closed.

Excellent: Batch creation of similar instances
Lack: instances use similar properties, resulting in a waste of memory and the inability to differentiate the type of the object

3. Create literally

Excellent: Simple and Direct
Missing: unable to build similar objects in batches

// Literally created objects use the constructor attribute instead of pointing to the instance, but to the object // use the literal to create var per1 = {name: "Ailer", constructor: per1, age: 12, gender: "female", holobby: "play", eat: function () {console. log (this. name) ;}} per1.eat (); // ailer per1.name = "lemon"; per1.eat (); // lemon console. log (typeof per1); // Object console. log (per1.constructor = Object); // true

4. new + Constructor

// The constructor creates an object. Its Sub-objects are not identified by instanceof. All new + obj objects are created. // The object is identified, but some code areas are still wasted; ==> create a prototype. // create a js object. new + constructor. // 1: Create a constructor. | generally, the first letter is uppercase. function CreatePerson (name, age) {// 2: attaches the property | method of an object to the this pointer. When the function is called to create an object, the this pointer points to the new object. // this is added to this object. name = name; this. age = age;/* this. speak = function () {// here this also points to the creation object console. log (this. name + "hello") ;}}/* CreatePerson. prototype. gender = "20"; CreatePerson. prototype. ea = function () {console. log (this. name + "sfd");} * // _ proto __: yes: Prototype attribute in the instance object, point to the prototype object corresponding to the corresponding constructor // [[prototype] // call var per1 = new CreatePerson ("ailer", "20 "); var per2 = new CreatePerson ("relia", "18"); console. log (per1 instanceof CreatePerson); // = true console. log (per2 instanceof CreatePerson); // ==> true console. log (per1.speak = per2.speak); // = false indicates that the system has opened up two different code zones, resulting in a waste of memory.

It is convenient to create a constructor literally. The constructor is a common Constructor (factory mode). The sub-object instanceof is not recognized and memory is wasted. The new + constructor is used to identify sub-objects, however, some code is still repeated, and the memory is wasted. The prototype code is generated to solve the problem.

V. prototype mode

Function CreateAnimal (name, age) {// 1.2: bind the external parameter to the instance attribute this. name = name; this. age = age;} // 1.3 bind the same property to the prototype (prototype property, Prototype Method) CreateAnimal. prototype. gender = "male"; CreateAnimal. prototype. style = function () {console. log (this. name + "ailers") ;}; // 2: Call the constructor to create the object var cat1 = new CreateAnimal ("xiaohua", "2 "); var cat2 = new CreateAnimal ("xiaohua", "2"); cat1.style (); console. log (cat1.style = cat2.style); // Method The reference address is the same, and attributes are placed in the prototype object, save address // instanceof can be used to determine which function the object belongs to. // The constructor builder can also be used to determine which constructor the object belongs. property points to its constructor // instanceof and constructor difference console. log (cat1 instanceof CreateAnimal); // true console. log (cat1 instanceof Object); // true console. log (cat1.constructor = CreateAnimal); // true console. log (cat1.constructor = Object); // the prototype of the constructor also has the constructor attribute, which indicates the constructor console. log (Cr EateAnimal. prototype. constructor = CreateAnimal); // true // in determines whether this attribute exists in this object. This attribute is an instance attribute or a prototype // alert ("name" in cat1) // true // alert ("gender" in cat1); // true // hasOwnProperty: determines whether an attribute is an instance attribute, if the property inherited from the prototype is true, else does not exist | false is not returned; console. log (cat1.hasOwnProperty ("aaa"); // if the property does not exist, false console is returned. log (cat1.hasOwnProperty ("name"); // true instance property console. log (cat1.hasOwnProperty ("style"); // false the returned prototype property is False // retrieve the prototype property by traversing the property // determine whether the parameter is the console of the prototype property tool. log (isPrototype ("gender", cat1); // true function isPrototype (proString, obj) {if (proString in obj) {if (! Obj. hasOwnProperty (proString) {return true;} else {return false;}/* function isProperty (object, property) {// determine whether a property return exists in the prototype! Object. hasOwnProperty (property) & (property in object );}*/

Dynamic Prototype

// Initialize the prototype function per (name, age, gender) {this. name = name; this. age = age; this. gender = gender; // only execute if (typeof this. sayName! = "Function") {Person. prototype. sayName = function () {alert (this. name );}}}

The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.