Home > Web Front-end > JS Tutorial > body text

How js creates objects and its characteristics

不言
Release: 2018-07-17 15:10:23
Original
1515 people have browsed it

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();
Copy after login

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('小米');
Copy after login

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();
Copy after login

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;原因:都是在原型下面,在内存中只存在一份,地址相同
Copy after login

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

5. Literals

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

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!