Ways to create objects in JavaScript

Source: Internet
Author: User
Tags uppercase letter hasownproperty

1. Factory mode

Use functions to encapsulate the details of creating objects with specific interfaces. However, this approach does not solve the problem of determining object types.

functionCreateperson (name,age,job) {varn \NewObject (); O.name=name; O.age=Age ; O.job=job; O.sayname=function() {alert ( This. name);} returno;}varPerson1 = Createperson ("Nicholas", "Software Engineer"); Console.log (Person1.name); //NicholasvarPerson2 = Createperson ("Sofia", "Docter");p erson2.sayname (); //Sofia

2. Constructor mode

You can define the properties and methods of a custom object type by creating a custom constructor. Constructors should always start with an uppercase letter; To create a new instance of a constructor, you must use the new operator.

functionPerson (name,age,job) { This. Name =name;  This. Age =Age ;  This. Job =job;  This. Sayname =function() {alert ( This. Name); };}varPerson1 =NewPerson ("Nicholas", "Chemical Engineer");varPerson2 =NewPerson ("Sofia", "Executive Manager"); Console.log (Person1instanceofObject);//trueConsole.log (Person1instanceofperson);//trueConsole.log (Person1.sayname==person2.sayname);//false

You can use the constructor pattern to determine the type of an object, but it is like this to write an object method inside the constructor so that each method is recreated on each instance. Functions created in this way cause different scope chains and identifiers to be parsed, so functions with the same name on different instances are not equal.
However, it is completely unnecessary to create different function instances of the same task. The function can be defined outside the constructor to resolve the problem.

functionPerson (name,age,job) { This. Name =name;  This. Age =Age ;  This. Job =job;  This. Sayname =Sayname;}functionSayname () {alert ( This. Name)}varPerson1 =NewPerson ("Nicholas", "Chemical Engineer");varPerson2 =NewPerson ("Sofia", "Executive Manager"); Console.log (Person1.sayname ()); //NicholasConsole.log (Person2.sayname ());//SofiaConsole.log (Person1instanceofObject);//trueConsole.log (Person1instanceofperson);//true

However, if the object needs to define many methods, it needs to define many global functions, then the custom reference type is not encapsulated.

3. Prototype mode

Each function has a prototype property, which is a pointer to an object, the prototype object, that is used to contain properties and methods that can be shared by all instances of a particular type. This allows all object instances to be shared by adding properties and methods directly to the prototype object.

functionPerson () {}person.prototype.name= "Nicholas"; Person.prototype.age= 29; Person.prototype.job= "Chemical Engieer"; Person.prototype.sayName=function() {alert ( This. Name); };varPerson1 =NewPerson ();p erson1.sayname (); //NicholasvarPerson2 =NewPerson (); Console.log (person2.age); // inConsole.log (Person.prototype.isPrototypeOf (Person1));//trueConsole.log (object.getprototypeof (Person1) ==person.prototype);//truePerson1.name= "Lisa";   Console.log (Person1.name); Lisaconsole.log (Person1.hasownproperty ("Name"));//true

By default, all prototype objects automatically get a constructor (constructor) property, which is a pointer to the function where the prototype property is located. After a custom constructor has been created, its prototype object will only get the constructor property by default. When the constructor is called to create a new instance, the inside of the instance contains a pointer (internal property), a prototype object that points to the constructor, and in ES5 [[Prototype]]. Although there is no standard way to access [[Prototype] in scripts, Firefox, Safari, and chrome support an attribute _proto_ on each object.

However, when overriding the entire prototype object, when Person.prototype is set to a new object (as follows), the constructor property becomes the constructor property of the new object (pointing to the object constructor) and no longer points to the person function.

person.prototype={      name:"Nicholas      "      , "software Engineer      ",  function() {          alert (this. name);}}

If the constructor property is important, you can add Constructor:person to the new prototype object, but the [[Enumerable]] attribute of the constructor property is set to true. is not enumerable by default, False.

You can determine whether an object instance belongs to an object prototype by using the isPrototypeOf () method. This method returns True if [[Prototype]] of the instance points to an object that calls the isPrototypeOf () method.

In ES5, a new method is added, object.getprototypeof (), which returns the value of [[Prototype]].

Use the hasOwnProperty () method to detect whether a property exists in an instance or exists in a prototype. This method returns true only if the given property exists in the object instance.

4. Combination of constructor mode and prototype mode

This type of constructor and prototype mix is currently the most widely used method of creating custom types in sub-ECMAScript. Each instance will have its own copy of the instance properties, as well as a reference to the method, which saves memory in a very low amount.

function Person (name,age,job) {    this.name = name;    This.age = Age ;    This.job = job;    This.friends = ["Shelby", "Court"];}

person.prototype={
Construtor:person,
sayname:function{
alert (this.name);
}
}

var person1=new person ("Nicholas", "Software Engineer");
var person2=new person ("Greg", "Chemical Engineer");
Person1.friends.push ("Sofia");
Console.log (person1.friends); ["Shelby", "Court", "Sofia"]
Console.log (person2.friends); ["Shelby", "Court"]

5. Dynamic Prototyping Mode

Use both constructors and prototypes to initialize the prototype only if necessary.

function Person (name,age,job) {   // attribute this    . name = name;     this. Age = Age ;     this. Job = job;     // Method   if (typeofthis. Sayname! = "function") {    Person.prototype.sayName=function  () {       alert (this. name);}}

6. Secure constructor Mode

A

Prudent object, which refers to an object that does not have a public property, and the method does not refer to this. A safe object is best used in some secure environments (where this and new are forbidden in the environment), or when data is being changed by other applications.

 function   Createperson (name,age,job) {  var  o = new      Object ();  //  define private variables and functions  //  Add method  O.sayname = function   () {alert (name);}   ;  //  return object  return   o;}  var  Friend=person ("Sofia", "Chemical Engineer"      //  "Sofia"  

In the above example, in addition to calling the Sayname () method, there is no other way to access the original data member that is passed into the constructor.

Ways to create objects in JavaScript

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.