JavaScript Object creation Pattern Instance Rollup _javascript tips

Source: Internet
Author: User
Tags instance method

The example in this article summarizes the JavaScript object creation pattern. Share to everyone for your reference, specific as follows:

It's easy to create objects in JavaScript, you can use object literals or constructors. The common patterns for creating objects are as follows:

A. Factory model

The factory pattern abstracts the process of specific objects, using functions to encapsulate the details of creating objects with the special ING interface.
As follows:

function Createanimal (name, age) {
  var o = new Object ();
  O.name = name;
  O.age = age;
  O.sayname = function () {
    alert (this.name);
  }
  return o;
}
var cat = Createanimal ("Cat",);
var dog = Createanimal ("Dog", 3);

Although the factory model solves the problem of creating multiple similar cashes, it does not solve the problem of object recognition.

Two. Constructor pattern

A constructor pattern can create objects of a particular type.

function Animal (name, age) {
  this.name = name;
  This.age = age;
  This.sayname = function () {
    alert (this.name);
  }
}
var cat = new Animal ("Cat",);
var dog = new Animal ("Dog", 3);

You can use the object's constructor property or instanceof operator to identify the object type.

Cat.constructor = = Animal//True
cat instanceof Animal//True

Three. Prototype mode

Each function has a prototype (prototype) attribute. This property is a pointer to an object, and the purpose of the object is to contain properties and methods that can be shared by all instances of a particular type.

The advantage of using a prototype object is that all object instances can share the properties and methods it contains.

function Animal () {}
Animal.prototype.name = "Animal";
Animal.prototype.age = 1;
Animal.prototype.sayName = function () {
  alert (this.name);
}
var test1 = new Animal ();
Test1.sayname (); "Animal"
var test2 = new Animal ();
Test2.sayname (); "Animal"
alert (test1.sayname = = test2.sayname);//True

Or:

function Animal () {}
Animal.prototype = {
  constructor:animal,
  name: "Animal",
  age:1,
  Sayname:function () {
    alert (this.name);
  }
};

All the attributes in the prototype are shared by many instances, and the corresponding properties in the prototype can be hidden by adding a property with the same name on the instance. However, for properties that contain reference type values, the problem is more obvious, as follows:

function Animal () {}
Animal.prototype = {
  constructor:animal,
  name: "Animal",
  age:1,
  hobbies: [" Dance "," Sing "," Play "],
  sayname:function () {
    alert (this.name);
  }
;
var cat = new Animal ();
var dog = new Animal ();
Cat.hobbies.push ("Sleep");
alert (cat.hobbies); "Dance", "Sing", "Play" and "Sleep"
alert (dog.hobbies);//"Dance", "Sing", "Play", "Sleep"
alert (cat.hobbies = = = Dog.hobbies); True

Four. Combined use of constructor patterns and prototype patterns

function Animal (name, age) {
  this.name = "Animal";
  This.age = 1;
  This.hobbies = ["Dance", "Sing", "Play"];
}
Animal.prototype = {
  constructor:animal,
  sayname:function () {
    alert (this.name);
  }
};
var cat = new Animal ("Cat", 2);
var dog = new Animal ("Dog", 3);
Cat.hobbies.push ("Sleep");
alert (cat.hobbies); "Dance", "Sing", "Play" and "Sleep"
alert (dog.hobbies);//"Dance", "Sing", "Play"
alert (cat.hobbies = = Dog.hobbies); False
alert (cat.sayname = = dog.sayname);//True

Five. Dynamic Prototyping mode

function Animal (name, age) {
  this.name = name;
  This.age = age;
  if (typeof this.sayname!= "function") {
    Animal.prototype.sayName = function () {
      alert (this.name);
    }
  }
}
var cat = new Animal ("Cat",);
Cat.sayname (); "Cat"

When using dynamic prototyping mode, you cannot use object literals to override prototypes. If you rewrite the prototype if you have already created an instance, you will sever the connection between the existing instance and the new prototype.

Six. Parasitic structural function pattern

The basic idea of a parasitic constructor pattern is to create a function that encapsulates only the code that creates the object and then returns the newly created object.

On the surface, this function looks like a typical constructor. In addition to using the new operator, this pattern looks exactly like the factory pattern. When a constructor does not return a value, the new object instance is returned by default. By adding a return statement at the end of the constructor, you can override the value returned when the constructor is called.

function Animal (name, age) {
  var o = new Object ();
  O.name = name;
  O.age = age;
  O.sayname = function () {
    alert (this.name);
  }
  return o;
}
var cat = new Animal ("Cat",);
Cat.sayname (); "Cat"

Because there is no relationship between the returned object and the stereotype of the constructor or constructor, you cannot rely on the instanceof operator to determine the object type.

It is recommended that you do not use this mode when you can use a different pattern.

Seven. Safe constructor mode

The safe constructor pattern is similar to the parasitic constructor pattern, but there are two different points:

One is that the instance method of the newly created object does not reference this;

The second is not applicable to the new operator call constructor.

function Animal (name, age) {
  var o = new Object ();
  O.name = name;
  O.age = age;
  var msg = "Hello, I ' m";
  O.sayname = function () {
    alert (msg + this.name);
  }
  return o;
}
var cat = new Animal ("Cat",);
Cat.sayname (); "Hello, I ' m cat"

The secure constructor pattern is suitable for certain security execution environments.

For more on JavaScript related content to view the site topics: "JavaScript object-oriented Tutorial", "javascript json operation tips Summary", "JavaScript switching effects and techniques summary", " JavaScript Search Algorithm Skills Summary, "JavaScript animation effects and techniques Summary", "JavaScript Error and debugging skills Summary", "JavaScript data structure and algorithm skills summary", "JavaScript traversal algorithm and skills summary" and The summary of JavaScript mathematical operational usage

I hope this article will help you with JavaScript programming.

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.