Schema rollup for creating objects in JavaScript _javascript tips

Source: Internet
Author: User
Tags hasownproperty

Schema rollup for creating objects in JavaScript

**javascript Create object mode:

Object literal Amount
Factory mode
Constructor pattern
Prototype mode
Combining constructors and prototype patterns
Prototype dynamic mode
**

Most object-oriented languages have the concept of a class that allows you to create multiple objects with the same methods and properties. While JavaScript is technically an object-oriented language, JavaScript has no concept of class, and everything is an object. Any object is an instance of a reference type that is created from an existing reference type, or a reference type that can be native or custom.

1, Object literal quantity

var person = {
    name: ' Nicholas ';
    Age: ' All ';
    Job: "Software Engineer"
    sayname:function () {
      alter (this.name);
  }
}

The example creates an object named person and adds three attributes (Name,age,job) and a Method (Sayname ()) to it, where the Sayname () method displays the THIS.name (resolved to Person.name) value.

Object literals can be used to create a single object, but there is an obvious drawback to this method: creating many objects with the same interface produces a lot of duplicate code.

2. Factory mode

The factory model is a well-known design pattern in the Software engineering field, which abstracts the process of creating specific objects and uses functions to encapsulate the details of creating objects with specific interfaces.

function Createperson (name,age,job) {
  var o = new object{};
  O.name=name;
  O.age=age;
  O.job=job;
  O.sayname=function () {
    alert (this.name);
  };
  return o;
}
var Person1=creatperson ("Nicholas", "Software Engineer");
var Person2=creatperson ("Greg", "student");

Function creatperson{} can build a person object that contains all the necessary information based on the accepted parameters. You can call this function countless times, and each time you return an object that contains a method of three properties.

Although the factory model solves the problem of creating multiple similar objects, it does not solve the problem of object recognition (i.e. how to know the type of an object).

3, the constructor function pattern

function Person (name,age,job) {
  this.name = name;
  This.age = age;
  This.job = job;
  This.sayname = function () {
    alert (this.name);
  }
}
Create an instance of person by using the new operator
var person1 = new Person ("Nicholas", "Software Engineer");
var person2 = new Person ("Greg", "student");
Person1.sayname (); Nicholas
person2.sayname ();//greg

Unlike the factory model,

Create object not shown

Assign properties and methods directly to the This object

No return statement

To create a new instance of person, you must use the new operator. 4 Steps to call a constructor:

Create a new object

Assigns a constructor's scope to a new object (this points to this new object)

Executing code in a constructor

return new Object

All objects created in this example are both an instance of object and a person instance. Can be validated by the instanceof operator.

Alert (Person1 instanceof Object);//true

The constructor pattern also has its own problem, in fact, the Sayname method is recreated on each instance, and it should be noted that the method created by instantiation is not equal, and the following code can prove

Alert (Person1.sayname = = person2.sayname);//false

The method can be moved to the outside of the constructor as a global function to solve the problem.

function Person (name,age,job) {
  this.name = name;
  This.age = age;
  This.job = job;  
}
function Sayname () {
    alert (this.name);
  }

A global function created globally can actually be invoked only by instances created by person, which is a bit of a misnomer; If the object needs to be defined very well, then many global functions are defined, and the encapsulation is missing.

4. Prototype mode

Each function created in JavaScript has a prototype (prototype) attribute, which is a pointer to an object that contains properties and methods that can be shared by all instances of a particular type (let all object instances share its properties and methods)

function person () {}
  Person.prototype.name = "Nicholas";
  Person.prototype.age =;
  Person.prototype.job = "Software Engineer";  
  Person.prototype.sayName () {
    alert (this.name);
  };
 var person1 = new Person ();
 Person1.sayname (); Nicholas
alert (person1.sayname = = person2.sayname);//true

The above code does these things:

Defines a constructor Person,person function that automatically obtains a prototype property that contains only one constructor property that points to the person
Add three properties through Person.prototype, and a method

Creates an instance of person and then invokes the Sayname () method on the instance

Show the relationship between objects by using the person constructor and Person.prototype to create an instance of code

Show the relationship between objects by using the person constructor and Person.prototype to create an instance of code

The diagram shows the relationship between the person constructor, the prototype property of the man, and the two instances of the. The Person.prototype points to the prototype object, and the Person.prototype.constructor has the person referred back. In addition to containing the constructor property, the prototype object contains additional properties and methods that have been added later, and two instances of person, Person1 and Person2, contain an internal property that points only to Person.prototype.

Call procedure for the Sayname () method:

Finding the LogName () method on the Person1 instance found no such method, and traced it back to the Person1 prototype

Find the Sayame () method on the Person1 prototype, and then invoke the method

Based on such a lookup process, we can prevent the instance from accessing the same name on the prototype by defining an attribute of the same name in the prototype on the instance, and it should be noted that doing so does not remove the attribute with the same name on the prototype, just block instance access.

function person () {}
  Person.prototype.name = "Nicholas";
  Person.prototype.age =;
  Person.prototype.job = "Software Engineer";  
  Person.prototype.sayName () {
    alert (this.name);
  };
 var person1 = new Person ();
 var person2 = new Person ();
 Person1.name= "Greg"
alert (person1.name)//greg from Instance
alert (person2.name)//nicholas from prototype

Use the delete operator to completely remove an instance property

Delete Person1.name;
Alert (Person1.name)//nicholas from prototype

Use the hasOwnProperty () method to detect whether an attribute exists in an instance or in a prototype

function person () {}
  Person.prototype.name = "Nicholas";
  Person.prototype.age =;
  Person.prototype.job = "Software Engineer";  
  Person.prototype.sayName () {
    alert (this.name);
  };
 var person1 = new Person ();
 var person2 = new Person ();
 Alert (Person1,hasownproperty ("name"));//false
 person1.name= "Greg"
alert (person1.name)//greg from an instance
 Alert (Person1,hasownproperty ("name")),//true
alert (person2.name)//nicholas from prototype
 alert (Person2, hasOwnProperty ("name"));//false
 delete person1.name;
Alert (Person1.name)//nicholas from prototype
 alert (Person1,hasownproperty ("name"));//false

The following illustration shows the relationship between an instance and a prototype under different circumstances

Simple prototype syntax

function person () {}
 person.prototype={
 name: "Nicholas",
 age:22,
 job: "Software Engineer" 
 , Sayname:function () {
    alert (this.name);
    }
  };

The constructor attribute is no longer pointing to person in the code above, and the object's type cannot be determined by constructor. You can set him back to the appropriate value as follows

function person () {}
 person.prototype={
 Constructor:person,
 name: "Nicholas",
 age:22,
 Job: "Software Engineer",  
 sayname:function () {
    alert (this.name);
    }
  ;

Resetting the constructor property causes its [[enumerable]] attribute to be set to true, and by default, the native constructor property is not enumerable and can be changed using the Object.defineproperty () method.

Object.defineproperty (Person.prototype, "constructor", {
  enumerable:false,
  Value:person
});

The process of looking up a value in a prototype is a search, and any modifications made by the prototype object can be immediately reflected from the instance.

var friend=new person ();
Person.prototype.sayhi=function () {
  alert ("Hi);
}
Friend,sayhi ()//"HI" (no problem)

The person instance is created before adding a new method, but can still access the newly added method because of the loose connection between the instance and the prototype
After you rewrite the prototype object

function person () {}
var friend=new person ();
 person.prototype={
 Name: "Nicholas",
 age:22,
 job: "Software Engineer", 
 sayname:function () {
    alert (this.name);
    }
  ;
  Friend.sayname ();//error

An error occurred while calling Friend.sayname () because the prototype that friend pointed to does not contain the attribute named in the field, as shown in the following figure.

Problem with a prototype object

The prototype object omits the process of passing initialization parameters for the constructor, and all forces obtain the same property value by default. The biggest problem with the prototype model is that it is shared by nature. The problem is more serious when the prototype model contains properties for reference types. Look at the example below.

function person () {}
 person.prototype={
 Constructor:person,
 name: "Nicholas",
 age:22,
 job: " Software Engineer ",  
 friends:[" Shelby "," Court "],
 sayname:function () {
    alert (this.name);
    }
  ;
  var person1=new person ();
  var person2=new person ();
  Person1.friend.push ("Van");
  alert (person1.friends);//"Shelby,court,van"
  alert (person2.friends);//"Shelby,court,van"
 alert ( Person1.friends==person2.friends);//true

5. Combined use of constructor patterns and prototype patterns

Combined using constructor patterns and prototype patterns, constructors are used to define instance properties, which are used to define methods and shared properties. Each instance has a copy of its own instance attribute, and can also share a reference to the method, saving the maximum amount of memory.

function Person (name,age,job) {
  this.name = name;
  This.age = age;
  This.job = job;  
  this.friends=["Shelby", "Court"];
}
person.prototype={
 Constructor:person,
 sayname:function () {
    alert (this.name);
    }
  }
var person1=new person ("Nicholas", "Software Engineer");
var person2 = new Person ("Greg", "student");
Person1.friend.push ("Van");
  alert (person1.friends);//"Shelby,court,van"
  alert (person2.friends);//"Shelby,court"
 alert ( person1.friends==person2.friends);//false
 alert (person1.sayname==person2.sayname);//true

6. Dynamic prototype mode

The prototype dynamic pattern encapsulates all the information that is required into the constructor, using an if statement to determine whether a property exists in the prototype, and if it does not exist (at the time of the first call to the constructor), execute the prototype initialization code inside the IF statement.

function Person (name,age) {
  this.name = name;
  This.age = age;
  This.job =job;
Method
  if (typeof this.sayname!= ' function ') {
  Person.prototype.sayName = function () {
      alert (this.name);
    };   
  }
}
var friend = new person (' Nicholas ', ' n ', ' Software Engineer ');//First Call constructor, at which time the prototype
var person2 = new Person (' Amy ', ' 21 ');//At this point the Sayname () method already exists and will not modify the prototype

Recommended reading:

JS object-oriented common ways to create objects (Factory mode, constructor pattern, prototype mode)

The above is a small set for you to introduce the JavaScript in the creation of objects in the model, I hope to help you!

Related Article

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.