Several methods for creating objects in JavaScript

Source: Internet
Author: User
Tags hasownproperty

Several methods for creating objects in JavaScript

** JavaScript Object Creation Mode:

Object literal factory mode constructor mode prototype mode combined with constructor and prototype mode prototype dynamic mode
**
Most object-oriented languages have the concept of a class. You can create multiple objects with the same methods and attributes through the class. Although technically speaking, javascript is an object-oriented language, javascript has no class concept and everything is an object. Any object is an instance of a reference type and is created through an existing reference type. The reference type can be native or custom.

1. Object literal volume

var person = {        name : 'Nicholas';        age : '22';        job :"software Engineer"        sayName: function() {            alter(this.name);    }}
In this example, create an object named person and add three attributes (name, age, job) and a method (sayName () to it () to display this. name (resolved to person. name.

The object literal can be used to create a single object, but this method has an obvious disadvantage: using the same interface to create many objects will produce a lot of repeated code.

2. Factory Model
The factory model is a well-known design pattern in the software engineering field. The factory pattern abstracts the process of creating a specific object and uses functions to encapsulate the details of creating objects with a specific interface.

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",22,"software Engineer");var person2=creatPerson("Greg",24,"student");
The creatPerson {} function can construct a Person object containing all necessary information based on the accepted parameters. This function can be called countless times, and an object containing three attributes and one method is returned each time.

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 var person1 = new Person ("Nicolas", 22, "software Engineer") for Person using the new operator "); var person2 = new Person ("Greg", 24, "student"); person1.sayName (); // niklasperson2.sayname (); // Greg

Different from the factory model

The created object that is not displayed directly assigns the attributes and methods to this object without the return statement.

To create a new instance of Person, you must use the new operator. Perform the following four steps to call the constructor:

Create a new object and assign the scope of the constructor to the new object (this points to this new object). Execute the code in the constructor and return the new object.

All objects created in this example are both Object instances and Person instances. It can be verified by the instanceof operator.

alert(person1 instanceof Object);//truealert(person1 instanceof Person);//true

The constructor mode also has its own problems. In fact, the sayName method is re-created on each instance. Note that the methods created by instantiation are not equal. The following code proves that
Alert (person1.sayName = person2.sayName); // false
You can move the method to the external part of the constructor as a global function to solve this problem.

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

The global functions created in the global environment can only be called by the instance created by Person, which is a bit out of the real name. If the object needs to be defined with the correct method, many global functions must be defined, lack of encapsulation.
4. Prototype
Each function created in JavaScript has a prototype attribute, which is a pointer pointing to an object, includes attributes and methods that can be shared by all instances of a specific type (so that all object instances can share their attributes and methods)

function Person() {}   Person.prototype.name ="Nicholas";   Person.prototype.age = 22;   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 the following:

Defines a constructor Person. The Person function automatically obtains a prototype attribute. By default, this attribute contains only one constructor attribute pointing to Person through Person. add three properties for prototype, create an instance of Person with a method, and then call the sayName () method on the instance.
Use the Person constructor and the Person. prototype code to create an instance as an example to show the relationship between objects.

The figure shows the relationship between the Person constructor, the prototype property of the Person, and the two instances of the Person. Person. prototype points to the prototype object. Person. prototype. constructor indicates that Person is returned. In addition to the constructor attribute, the prototype object also contains other attributes and Methods subsequently added. The two instances of Person, person1 and person2, both contain an internal attribute that only points to Person. prototype.
SayName () method call Process: Find the logName () method on the person1 instance. If this method is not found, it is traced back to the prototype of person1.

Search for the sayame () method on the prototype of person1. With this method, call this method.

Based on such a search process, we can define the Same Name attribute in the prototype on the instance to prevent the instance from accessing the Same Name attribute on the prototype. Note that, in this way, the attributes with the same name on the prototype are not deleted, but the instance access is blocked.

Function Person () {} Person. prototype. name = "Nicolas"; Person. prototype. age = 22; 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 comes from the instance alert (person2.name) // Nicolas comes from the prototype

You can use the delete operator to completely delete instance attributes.

Delete person1.name; alert (person1.name) // Nicolas from the prototype

The hasOwnProperty () method can be used to check whether an attribute exists in an instance or a prototype.

Function Person () {} Person. prototype. name = "Nicolas"; Person. prototype. age = 22; 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 comes from the instance alert (person1, hasOwnProperty ("name"); // truealert (person2.name) // Nicolas from the prototype alert (person2, hasOwnProperty ("name"); // false delete person1.name; alert (person1.name) // Nicolas from the prototype alert (person1, hasOwnProperty ("name"); // false

Displays the relationship between the instance and the prototype in different situations.

Simple prototype syntax <喎?http: www.bkjia.com kf ware vc " target="_blank" class="keylink"> VcD4NCjxwcmUgY2xhc3M9 "brush: java;"> function Person() {} Person.prototype={ name :"Nicholas", age : 22, job : "software Engineer", sayName:function(){ alert(this.name); } };

In the code above, the constructor attribute no longer points to Person, and the object type cannot be determined through constructor. You can set it back to an 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 attribute will result in its [[Enumerable] attribute being set to true. By default, native constructor attributes cannot be enumerated and objects can be used. defineProperty () method to change

Object.defineProperty(Person.prototype,"constructor",{    enumerable:false,    value:Person});

The process of searching values in the prototype is a search. Any modifications made to the prototype object can be immediately reflected on the instance.

Var friend = new Person (); Person. prototype. sayHi = function () {alert ("hi) ;}friend, sayHi (); //" hi "(no problem)

The person instance is created before the new method is added, but you can still access the newly added method,The reason is the loose connection between the instance and the prototype.
After rewriting 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

The error occurs when you call friend. sayName () because the prototype pointed to by friend does not contain attributes named by this field, for example.

Prototype Object Problems
The prototype object skips the process of passing initialization parameters for the constructor. All forces get the same attribute value by default. The biggest problem with the prototype model is its shared nature. When the prototype model contains attributes of the reference type, the problem is serious. Let's 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 the constructor mode and prototype mode
In the constructor mode and prototype mode, constructor is used to define instance attributes. The prototype is used to define methods and shared attributes. In this way, each instance has its own copy of the Instance attribute, and can also share the reference to the method, saving the memory to the maximum extent.

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",22,"software Engineer");var person2 = new Person("Greg",24,"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
The prototype dynamic mode encapsulates all required information into the constructor, and uses the if statement to determine whether an attribute in the prototype exists. if it does not exist (when this constructor is called for the first time ), execute the prototype initialization code in 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 ', '22', 'Software engine'); // the first time the constructor is called, the prototype var person2 = new Person ('amy ', '21') is modified. // The sayName () method already exists and the prototype will not be modified.

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.