Learn JavaScript Object-oriented Mastery 9 ways to create objects _javascript tips

Source: Internet
Author: User
Tags function definition

This article for everyone to share the JavaScript to create the object of 9 ways, for your reference, the specific content as follows

"1" uses the object constructor
[Disadvantage] creating many objects with the same interface produces a lot of duplicate code

var person = new Object ();
  Person.name = "Nicholas";
  Person.age =;
  Person.job = "Software Engineer";
  Person.sayname = function () {
  alert (this.name);
}

"2" uses object literals
[Disadvantage] creating many objects with the same interface produces a lot of duplicate code

var person = {
  Name: "Nicholas",
  age:29,
  job: "Software Engineer",
  sayname:function () {
    alert (this.name);
  }
;

"3" Factory mode: Abstract the process of creating a specific object, considering that a class cannot be created in ECMAScript, the developer invents a function that encapsulates the details of creating an object with a specific interface
[Disadvantage] solves the problem of creating multiple similar objects, but does not solve the problem of object recognition

function Createperson (name,age,job) {
  var o = new Object ();
  O.name = name;
  O.age = age;
  O.job = job;
  O.sayname = function () {
    alert (this.name);
  }
  return o;
}
var person1 = Createperson (' Nicholas ', +, ' software Engineer ');
var person2 = Createperson (' Greg ', ', ' doctor ');

"4" constructor pattern: No objects are explicitly created, attributes and methods are assigned directly to this object, no return statement
[Disadvantage] Each method is recreated on each instance

function Person (name,age,job) {
  this.name = name;
  This.age = age;
  This.jog = job;
  This.sayname = function () {
    alert (this.name);
  };
  //this.sayname = new Function (' Alert (this.name) ') that is logically equivalent to a declaration function;
var person1 = new Person ("Nicholas", "Software Engineer");
var person2 = new Person ("Greg", "Doctor");

"4.1" constructor extension mode: transfer function definition to external constructor
[Disadvantage 1] a function defined in a global scope can actually only be invoked by an object, which makes the global scope a bit of a misnomer
[Disadvantage 2] If the object needs to define many methods, it is necessary to define a number of global functions, this custom reference type has no encapsulation to speak of

function Person (name,age,job) {
  this.name = name;
  This.age = age;
  This.job = job;
  This.sayname = Sayname;
}
function Sayname () {
  alert (this.name);
}
var person = new person (' Little match ', ' student ')
person.sayname ();
Console.log (person);

"5" prototype mode: Each function we create has a prototype (prototype) attribute, which is a pointer to an object that is intended to contain properties and methods that can be shared by all instances of a particular type. If understood literally, prototype is the prototype object of an object instance created by calling the constructor

function person () {
  Person.prototype.name = "Nicholas";
  Person.prototype.age =;
  Person.prototype.job = "Software Engineer";
  Person.prototype.sayName = function () {
    alert (this.name);
  }
}
var person1 = new Person ();
Person1.sayname ();//"Nicholas"
var person2 = new Person ();
Person2.sayname ()//"Nicholas"
alert (person1.sayname = = person2.sayname);//true

"5.1" Simpler prototyping mode: to reduce unnecessary input, and to visually better encapsulate the functionality of the prototype, rewrite the entire prototype object with an object literal that contains all the properties and methods.
[Disadvantage] Resetting the constructor property in this way causes its [[enumerable]] attribute to be set to true, and the native constructor property is not enumerable by default

function person () {};
Person.prototype = {
  Constructor:person,
  name: "Nicholas",
  age:29,
  job: "Software Engineer",
  Sayname:function () {
    alert (this.name);
  }
};

"5.2" prototype model for solving enumerable problem

function person () {};
Person.prototype = {
  name: "Nicholas",
  age:29,
  job: "Software Engineer",
  sayname:function () {
    alert (this.name);
  }
;
Object.defineproperty (Person.prototype, "constructor", {
  enumerable:false,
  Value:person
});

[prototype mode disadvantage 1] The rewriting of a prototype object cuts off the connection between an existing prototype and a pre-existing object instance, which is still referenced by the original prototype.

function person () {}
var friend = new person ();
Person.prototype = {
  Constructor:person,
  name: "Nicholas",
  age:29,
  job: "Software Engineer",
  Sayname:function () {
    alert (this.name);
  }
};
Friend.sayname ();//error

[prototype mode disadvantage 2] a shared problem with reference type attributes is highlighted

function person () {}
Person.prototype = {
  Constructor:person,
  name: "Nicholas",
  age:29,
  Job: "Software Engineer",
  friend: ["Shelby", "Court"],
  sayname:function () {
    alert (this.name);
  }
};
var person1 = new Person ();
var person2 = new Person ();
Person1.friends.push ("Van");
alert (person1.friends);//["Shelby", "Court", "Van"];
alert (person2.friends);//["Shelby", "Court", "Van"];
Alert (Person1.friends = = person2.friends);//true

"6" Combination mode: Combining the constructor and prototype patterns is the most common way to create a custom type. The constructor pattern is used to define instance properties, which are used to define methods and shared properties. This blending pattern also supports passing parameters to constructors, which is a default mode for defining reference types

function Person (name,age,job) {
  this.name = name;
  This.age = age;
  This.job = job;
  This.friends = ["Shelby", "Court"];
}
Person.prototype = {
  Constructor:person,
  sayname:function () {
    alert (this.name);
  }  
}
var person1 = new Person ("Nicholas", "Software Engineer");
var person2 = new Person ("Greg", "Doctor");
Person1.friends.push ("Van");
alert (person1.friends);//["Shelby", "Court", "Van"];
alert (person1.friends);//["Shelby", "Court"];
Alert (Person1.friends = = person2.friends);//false
alert (person1.sayname = = person2.sayname);//true

"7" Dynamic prototyping mode: encapsulating all the information in a constructor, by initializing the prototype in the constructor (if necessary), and maintaining the advantage of using constructors and prototypes at the same time. In other words, you can determine whether you want to initialize a prototype by checking whether an existing method is valid.
[note] 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 instance

function Person (name,age,job) {
  //property
  this.name = name;
  This.age = age;
  This.job = job;
  Method
  if (typeof this.sayname!= "function") {
    Person.prototype.sayName = function () {
      alert (this.name);
    };
  }
}
var friend = new Person ("Nicholas", "Software Engineer");
Friend.sayname ();

"8" parasitic constructor pattern: Creates a function that encapsulates only the code that creates the object and then returns the newly created object

function Person (name,age,job) {
  var o = new Object ();
  O.name = name;
  O.age = age;
  O.job = job;
  O.sayname = function () {
    alert (this.name);
  };
  return o;
}
var friend = new Person ("Nicholas", "Software Engineer");
Friend.sayname ()//"Nicholas"

"Parasitic constructor pattern application" creates a special array with extra methods. Because the array constructor cannot be modified directly, you can use this pattern

function Specialarray () {
  //create array
  var values = new Array ();
  Add Value
  values.push.apply (values,arguments);
  Add method
  values.topipedstring = function () {return
    this.join (' | ');
  Returns the array return
  values;
}
var colors = new Specialarray ("Red", "Blue", "green");
Alert (colors.topipedstring ());//"Red|blue|green"  

"9" secure constructor mode: the so-called Safe object refers to an object that has no public properties and whose methods do not refer to this. Secure objects are best used in some security environments that prohibit the use of this and new, or when you prevent data from being changed by other applications.

function Person (name,age,job) {
  //Create the object to be returned
  var o = new Object ();
  Here you can define private variables and functions
  //Add methods
  O.sayname = function () {
    alert (name);
  Returns the object return
  o;
}
There is no other way to access the value of name
var friend = person ("Nicholas", "Software Engineer")
in addition to using the Sayname () method in an object created in a safe mode. Friend.sayname ()//"Nicholas"

The above is JavaScript to create the object nine kinds of way, hope to be helpful to everybody's study.

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.