Js-javascript common ways to create objects

Source: Internet
Author: User

1. Create a single object by using the object constructor or the objects literal

There are obvious drawbacks to these approaches: creating many objects with the same interface creates a lot of duplicate code. In order to solve this problem, there is a factory model.

2. Factory mode

Considering the inability to create a class in Es (ES6), the developer invented a function that encapsulates the details of creating an object with a specific interface. (The implementation is to create a good object within a function, and then return the object ).

 function   Createperson (name,age,job) {  var  o=new      Object ();    O.name  =name;    O.age  =age;    O.job  =job; O.sayname  =function   () {alert (    Span style= "COLOR: #0000ff" >this  .name);    };  return  0;}  var  Person1=createperson ("Nicholas", "Software Engineer"  var  Person2=createperson ("Greg", "Doctor"); 

The function Createperson () is able to construct a person object that contains all the necessary information based on the parameters that are accepted. 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 . With the development of JS, another pattern appeared.

3. Constructor Mode

Native constructors, such as object and array, will automatically appear in the execution environment at run time. In addition, you can create custom constructors that define properties and methods for custom object types.

function Person (name,age,job) {    this. name=name;      this. age= age;     this. job=job;     this. sayname=function() {        alert (this. name);}    ;} var person1=New person (...); var person2=new person (...);

Compared with the factory model, it has the following characteristics:

    1. Object not explicitly created;
    2. The properties and methods are assigned directly to the This object;
    3. no return statement;
    4. To create a new instance, you must use the new operator; (otherwise properties and methods will be added to the Window object)
    5. Object types can be detected using the instanceof operator

Problems with constructors:

Methods inside the constructor are created repeatedly, and functions with the same name in different instances are not equal . You can solve this problem by moving the method outside of the constructor, but you face a new problem: The encapsulation is not good.

These problems can be solved through prototype mode.

4. Prototype Mode

Each function we create has a prototype property, which is a pointer to an object, and the purpose of this object is to include properties and methods that can be shared by all instances of a particular type. (prototype is the prototype object of the object instance created by invoking the constructor).

 The advantage of using a prototype object is that you can have all object instances share the properties and methods that it contains. In other words, instead of defining the information for an object instance in the constructor, you can add that information directly to the prototype object.

function Person () {}person.prototype.name= "Nicholas"; Person.prototype.age=29; Person.prototype.job= "..."; Person.prototype.sayName=function() {    ...}; var person1=New person ();p erson1.sayname (); // "Nicholas"

It is more common to rewrite the entire prototype object with an object literal that contains all the properties and methods and reset the constructor property.

function Person () {}person.prototype={    name:' ... ', age    :',    job:' ... '  ,    sayname:function() {        ...    }};o Bject.defineproperty (Person.prototype,"constructor", {    enumerable:false,    Value:person,});

Problem with prototype object:

    1. He omitted to pass the initialization parameters for the constructor, and all instances would get the same property value by default, although this would bring some inconvenience to some extent, but not the biggest problem, the biggest problem was determined by the nature of their sharing.
    2. For properties that contain base values, you can hide the properties in the prototype by adding a property with the same name on the instance. Then, for values that contain reference data types , this can cause problems.

These problems result in a rare use of prototype patterns alone.

5. combination of constructor mode and prototype mode

This is the most common way to create custom types.

  The constructor pattern is used to define instance properties, and the prototype schema is used to define methods and shared properties . So each instance will have its own copy of the instance properties, but at the same time share a reference to the method, to maximize the memory savings. Arguments are also supported for passing the constructor function.

function Person (name,age,job) {    this. name=name;      this. age= age;     this. job=job;     this. friends=["S", "C"];} Person.prototype={    Constructor:person,    sayname:function() {        Alert (this. name);}    ; var person1=new person (...);
6. Dynamic prototype Mode
function Person (name,age,job) {    this. name=name;      this. age= age;     this. job=job;     if (typeofthis. sayname!= "function") {        Person.prototype.sayName=function  () {            alert (this. Name);     }}

only if Sayname () does not exist here will it be added to the prototype, which will only be executed when the constructor is first called . The modifications made to the prototype here can be immediately reflected in all instances.

7, Object.create ()

ES5 defines a method named Object.create () that creates a new object, where the first parameter is the prototype of the object, and the second parameter describes the properties of the object further.

8, another parasitic structural function mode and a secure constructor mode

Js-javascript common ways to create objects

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.