Several modes of creating objects in JavaScript

Source: Internet
Author: User
Tags hasownproperty

**javascript Create object pattern:

    • Object literal
    • Factory mode
    • Constructor mode
    • Prototype mode
    • Combining constructors and prototype patterns
    • Prototype dynamic mode
      **
      Most object-oriented languages have a concept of a class that allows you to create multiple objects with the same methods and properties. Although JavaScript is technically an object-oriented language, JavaScript does not have the 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, and the reference type can be either native or custom.

1. Object literal

var person = {        ‘Nicholas‘;        ‘22‘;        job :"software Engineer"        function() {            alter(this.name);    }}
例子中创建一个名为person的对象,并为它添加了三个属性(name,age,job)和一个方法(sayName()),其中,sayName()方法用于显示this.name(被解析为person.name)的值。

Object literals can be used to create a single object, but this approach has one obvious drawback: creating many objects with the same interface creates a lot of duplicated code.

2. Factory mode
Factory mode is a well-known design pattern in the field of software engineering, and Factory mode abstracts the process of creating concrete objects, using functions to encapsulate the details of creating objects with specific interfaces.

function  createperson   (name,age,job)  {    Span class= "Hljs-keyword" >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" , 22 ,  "software Engineer" ); var  Person2=creatperson ( "Greg" , 24 , " student ");  
函数creatPerson{}能够根据接受的参数构建一个包含所有必要信息的Person对象。可以无数次的调用这个函数,每次都会返回一个包含三个属性一个方法的对象。

Although the factory model solves the problem of creating multiple similar objects, it does not solve the problem of object recognition (that is, how to know the type of an object).
3. Constructor mode

 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 with the new operatorvarPerson1 =NewPerson ("Nicholas", A,"Software Engineer");varPerson2 =NewPerson ("Greg", -,"Student");p Erson1.sayname ();//nicholasPerson2.sayname ();//greg

Unlike the factory model,

    • Create objects that are not displayed
    • 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 the scope of the constructor to the new object (this points to the new object)
    • Executing the code in the constructor
    • return new Object

All objects created in this example are both instances of object and person instances. Can be verified by the instanceof operator.

instanceofObject);//trueinstanceof Person);//true

The constructor pattern also has its own problem, in fact, the Sayname method is recreated on each instance, and it is important to note that the methods created by instantiation are not equal, and the following code can prove
Alert (Person1.sayname = = person2.sayname);//false
You can resolve this problem by moving the method outside the constructor as a global function.

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

global functions created in the global context can actually only be called by instances created by person, which is a bit of a misnomer; If an object needs to define a very good method, it is necessary to define many global functions, which are lack of encapsulation.
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 (the properties and methods that allow all object instances to share it)

function person () {} person. Prototype. Name="Nicholas";Person. Prototype. Age= A;Person. Prototype. Job="Software Engineer"; Person. Prototype. Sayname() {alert (this. Name);};var person1 = new Person ();Person1. Sayname();//nicholasAlert (Person1. Sayname= = Person2. Sayname);//true

The above code does a few things:

    • Defines a constructor Person,person function automatically obtains a prototype property, which by default contains only one constructor property that points to person
    • Add three attributes via Person.prototype, and a method
    • Creates an instance of the person and then calls the Sayname () method on the instance
      Show the relationship between objects using the person constructor and the code for creating an instance of Person.prototype

      The diagram shows the relationship between the person constructor, the prototype property of the person, and the two instances of person. Person.prototype points to the prototype object, and Person.prototype.constructor refers back to the person. In addition to the constructor property contained in the prototype object and other properties and methods added later, the two instances of person person1 and Person2 contain an internal property that points only to Person.prototype.
      the call procedure for the Sayname () method :
    • Find the LogName () method on the Person1 instance, and find no such method, and trace back to the prototype of Person1
    • To find the Sayame () method on the Person1 prototype, this method is called

      Based on such a lookup procedure, we can prevent the instance from accessing the same name property on the prototype by defining the same name attribute on the instance, and it is important to note that doing so does not delete the same name attribute on the prototype, only blocking the instance access.

function person () {} person. Prototype. Name="Nicholas";Person. Prototype. Age= A;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 the prototype

Use the delete operator to completely remove instance properties

delete//Nicholas 来自原型

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

 function person() {} Person.prototype.name ="Nicholas"; Person.prototype.age = A; Person.prototype.job ="Software Engineer"; Person.prototype.sayName () {alert ( This. name); };varPerson1 =NewPerson ();varPerson2 =NewPerson (); Alert (Person1,hasownproperty ("Name"));//falsePerson1.name="Greg"Alert (Person1.name)//greg from an instanceAlert (Person1,hasownproperty ("Name"));//trueAlert (Person2.name)//nicholas from prototypeAlert (Person2,hasownproperty ("Name"));//false DeletePerson1.name;alert (Person1.name)//nicholas from prototypeAlert (Person1,hasownproperty ("Name"));//false

Demonstrates the relationship between an instance and a prototype in different situations

Simple prototype syntax

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

In the above code, the constructor property no longer points to person, and constructor cannot determine the type of the object. You can deliberately set him back to the appropriate value as follows

function Person() {} Person.prototype={ constructor:Person,  name :"Nicholas",  22,  "software Engineer",     sayName:function(){       alert(this.name);       }   };

Resetting the constructor property causes its [[Enumerable]] property to be set to true, 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 finding 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"(没有问题)

The person instance is created before the new method is added, but the newly added method can still be accessed because of the loose connection between the instance and the prototype
What happens after you rewrite a prototype object

function Person() {}var friend=new Person(); Person.prototype={  name :"Nicholas",  22,  "software Engineer",    sayName:function(){       alert(this.name);       }   };   friend.sayName();//error

An error occurred when calling Friend.sayname () because a friend pointed to a prototype that does not contain a property named in that field, such as.

problems with prototype objects
The prototype object omits the process of passing initialization parameters to the constructor, and all forces get the same attribute value by default. The biggest problem with the prototype model is that it has its shared nature. When a prototype model contains a property of a reference type, the problem is more serious. Take a look at the following example.

 function person() {} person.prototype={Constructor:person, Name:"Nicholas", Age: A, Job:"Software Engineer", friends:["Shelby","Court"], Sayname: function(){Alert This. name); }   };varperson1=NewPerson ();varPerson2=NewPerson (); Person1.friend.push ("Van"); alert (person1.friends);//"Shelby,court,van"alert (person2.friends);//"Shelby,court,van"alert (person1.friends==person2.friends);//true

5. Combination of constructor mode and prototype mode
In combination with constructor mode and prototype mode, constructors are used to define instance properties, and the prototype model is used to define methods and shared properties. Each instance will have its own copy of the instance properties, and it can also share references to the method, saving memory for the most part.

 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); }   }varperson1=NewPerson ("Nicholas", A,"Software Engineer");varPerson2 =NewPerson ("Greg", -,"Student");p Erson1.friend.push ("Van"); alert (person1.friends);//"Shelby,court,van"alert (person2.friends);//"Shelby,court"alert (person1.friends==person2.friends);//falsealert (person1.sayname==person2.sayname);//true

6. Dynamic prototype mode
The prototype dynamic pattern encapsulates all the information needed into the constructor, using the IF statement to determine if 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);          }; }}varFriend =NewPerson (' Nicholas ',' A ',' software Engineer ');//Initial call to constructor, at which time the prototype is modifiedvarPerson2 =NewPerson (' Amy ',' + ');//At this point the Sayname () method already exists and the prototype is no longer modified

Several modes of creating objects in JavaScript

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.