Home  >  Article  >  Web Front-end  >  How js creates objects and its characteristics

How js creates objects and its characteristics

不言
不言Original
2018-07-17 15:10:231492browse

There are many ways to create objects in js. Each method has its own advantages and disadvantages, so it is very important to choose a suitable way to create objects. The following content introduces several ways to create objects in js. .

1. Factory pattern

function createPerson(name){
   //1、原料
    var obj=new Object();
   //2、加工
    obj.name=name;
    obj.showName=function(){
       alert(this.name);
    }     
    //3、出场
     return obj; 
} 
var p1=createPerson('小米');
p1.showName();

Advantages: Solve the problem of creating similar objects

Disadvantages: You cannot know the type of an object

2. Constructor

function CreatePerson(name){
  this.name=name;
  this.showName=function(){
    alert(this.name);
  }
}
    var p1=new CreatePerson('小米');

Advantages: Some instances can be represented as a specific type

Disadvantages: The method will be recreated over and over again on each instance

3. Prototype

function Person(){}
Person.prototype.name="小米";
Person.prototype.showName=function(){
alert(this.name);
}
var p1=new Person();
p1.showName();

Advantages: Properties and methods are defined on the prototype, so each instance can share properties and methods

Disadvantages: Instance properties cannot be privatized

4. Hybrid (constructor prototype)

function CreatePerson(name){
  this.name=name;
}
  Create.prototype.showName=function(){
    alert(this.name);
  }
    var p1=new CreatePerson('小米');
    p1.showName();
   var p2=new CreatePerson('小米');
    p2.showName();
  alert(p1.showName==p2.showName);//true;原因:都是在原型下面,在内存中只存在一份,地址相同

Define properties through constructors, and define methods and shared properties through prototypes.

5. Literals

person={
  name:"小米",
  age:23
};

Related recommendations:

Examples of writing methods to create objects in JS

Various methods of creating js objects are described in detail

The above is the detailed content of How js creates objects and its characteristics. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn