JS create objects in several ways

Source: Internet
Author: User

Object-oriented is to put the property and operation properties of the method together as an interdependent whole-object, that is, the concept of owning classes, based on the class can create any number of instance objects, generally with encapsulation, inheritance, polymorphism characteristics!

ECMA-262 defines an object as: "A collection of unordered attributes whose properties can contain base value objects or functions." This means that the object is a set of values that do not have a specific order, where the value can be data or function.

Although the object constructor or object literal can create a single object, there is an obvious drawback to creating many objects using the same interface, resulting in a large amount of duplicate code. So the following patterns are produced.

1 Factory mode

function Createperson (name,age,job) {     var o = {};     O.name = name;     O.age = age;     O.job = job;     O.sayname = function () {           alert (this.name);};       return o; }    var = createperson ("Tanya", "Tanya", "female");    

Feature: This pattern abstracts the process of creating concrete objects. It uses functions to encapsulate the details of creating objects with specific interfaces.

Cons: There is no problem solving object recognition, and each time a new object is generated, a new function sayname is created, which allows each object to have its own version of Sayname, and in fact all objects share the same function.

2 constructor mode

function Createperson (name,age,job) {     this.name = name;     This.age = age;     This.job = job;     This.sayname = function () {           alert (this.name);};}    var Tanya =new Createperson ("Tanya", "a", "female");    

PS: The only difference between constructors and ordinary functions is that they are called differently: any function, as long as the constructor is called through the new operator, and vice versa.

Creating a new instance using the new operator goes through the following 4 steps:

(1) Create a new object

(2) Assign the scope of the constructor to the new object (this is the new object)

(3) Executing the code in the constructor (adding attributes to the new object)

(4) Returning new objects

The difference between a constructor and a factory pattern:

    • Create objects that are not displayed
    • Assigning properties and methods directly to the This object;
    • No return statement

The constructor solves the problem of object recognition (Tanya has a constructor property that points to Createperson), but like Factory mode, each method is recreated in each instance. We can move the function definition to the outside of the constructor to solve the problem, but there is no encapsulation to say.

3 prototype mode

Let's start with the prototype (prototype) attribute, where each function we create has a prototype property, which is a pointer to an object that is used to contain properties and methods that can be shared by all instances of a particular type.

All things are objects in Ps:js, but they are divided into two main categories: ordinary objects and Function objects. All function objects have a prototype property, and the normal object has no prototype property, only _proto_.

function Createperson () {}     createPerson.prototype.name = "Tanya";     CreatePerson.prototype.age = "a";     CreatePerson.prototype.job = "female";     CreatePerson.prototype.sayName = function () {           alert (this.name);};    var Tanya =new Createperson ();    

Although prototype mode solves the problem of constructors, each method is recreated in each instance again. However, all instances have the same property value by default, and the instance is generally owned by all of its properties.

4 combining the constructor pattern with the prototype mode

function Createperson (name,age,job) {     this.name = name;     This.age = age;     This.job = job; }  CreatePerson.prototype.sayName = function () {           alert (this.name);};    var Tanya =new Createperson ("Tanya", "a", "female");    

This is the most common way to create custom types, constructor patterns define instance properties, prototype patterns define methods, and shared properties.

5 Parasitic constructor mode

function Createperson (name,age,job) {     var o = {};     O.name = name;     O.age = age;     O.job = job;     O.sayname = function () {           alert (this.name);};       return o; }    var tanya =new Createperson ("Tanya", "a", "female");    

In addition to using the new operator to define the object and to call it a constructor, the other is identical to the factory schema definition. Because new is used at creation time, the implementation process is different (but the implementation process is not important) and the result is the same. It looks more elegant.

Parasitic constructors can be used in situations where the constructor is not adaptable, such as creating an existing type with an extra method (such as an array, date type, etc.), but not polluting the original type.

6 Secure constructor Mode

A secure object, which refers to an object that does not have a public property and whose method does not refer to this.

A secure constructor is similar to a parasitic constructor, but has a difference of 2 points: the instance method of the newly created object does not refer to this, and the constructor is not called with the new operator.

function Createperson (name, age, Job) {    var o = new Object ();     Private members    var NAMEUC = Name.touppercase ();    Public members    O.sayname = function () {        alert (name);    };    O.saynameuc = function () {        alert (NAMEUC);    };    return o;} var person = person ("Nicholas", +, "software Engineer");p erson.sayname (); "Nicholas" Person.saynameuc (); "NICHOLAS" alert (person.name);  Undefinedalert (PERSON.NAMEUC);  Undefined

Any member who wants to be private should not hang onto the property of the object o returned by Createperson, and hang it on the public. Here the private and public are from the formal analogy with other OO language, the implementation of the principle or JS in the scope, closure and object that set.

JS create objects in several ways

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.