Learn javascript object-oriented skills 9 ways to create objects, javascript9

Source: Internet
Author: User

Learn javascript object-oriented skills 9 ways to create objects, javascript9

This article shares nine ways to create javascript objects for your reference. The specific content is as follows:

[1] constructing functions using objects
[Disadvantage] using the same interface to create many objects will produce a large number of repeated Codes

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

[2] Using Object literal
[Disadvantage] using the same interface to create many objects will produce a large number of repeated Codes

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

[3] factory mode: abstracts the process of creating a specific object. Considering that classes cannot be created in ECMAScript, developers have invented a function that encapsulates the details of object creation using a specific interface.
[Disadvantage] it 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',29,'software Engineer');var person2 = createPerson('greg',27,'doctor');

[4] constructor mode: no explicit object is created, and attributes and methods are directly assigned to this object without a return statement.
[Disadvantage] Each method must be re-created on each instance.

Function Person (name, age, job) {this. name = name; this. age = age; this. jog = job; this. sayName = function () {alert (this. name) ;}; // logically equivalent to the declarative function // this. sayName = new Function ('alert (this. name) ');} var person1 = new Person ("Nicolas", 29, "software Engineer"); var person2 = new Person ("Greg", 27, "doctor ");

[4.1] constructor expansion mode: transfers the function definition to the external part of the constructor.
[Disadvantage 1] The function defined in the global scope can only be called by an object, which makes the global scope a bit out of name.
[Disadvantage 2] if the object needs to define many methods, many global functions need to be defined, and this custom reference type is not encapsulated.

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', '20', 'student ') person. sayName (); console. log (Person );

[5] prototype mode: each function we create has a prototype attribute, which is a pointer pointing to an object, the purpose of this object is to include attributes and methods that can be shared by all instances of a specific type. Prototype is the prototype of the object instance created by calling the constructor.

function Person(){  Person.prototype.name = "Nicholas";  Person.prototype.age = 29;  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 prototype: to reduce unnecessary input and visually better encapsulate prototype functions, rewrite the entire prototype object with a literal volume of all attributes and methods.
[Disadvantage] resetting the constructor attribute in this way will result in its [[Enumerable] attribute being set to true. By default, native constructor attributes cannot be enumerated.

function Person(){};Person.prototype = {  constructor : Person,  name: "Nicholas",  age: 29,  job: "software Engineer",  sayName : function(){    alert(this.name);  }};

[5.2] prototype mode for solving the 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 disadvantages 1] rewriting prototype objects cut off the relationship between existing prototype and existing object instances. They reference 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

[Disadvantages of prototype mode 2] prominent Sharing Problem of reference type attributes

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: constructor mode and prototype mode are the most common methods for creating custom types. The constructor mode is used to define instance attributes, while the prototype mode is used to define methods and shared attributes. This mixed mode also supports passing parameters to the constructor, which is a default mode for defining the reference type.

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",29,"Software Engineer");var person2 = new Person("Greg",27,"Doctor");person1.friends.push("Van");alert(person1.friends);// ["shelby","Court","Van"];alert(person1.friends);// ["shelby","Court"];alert(person1.friends === person2.friends);//falsealert(person1.sayName === person2.sayName);//true

[7] dynamic prototype mode: encapsulate all information in the constructor and initialize the prototype in the constructor (only if necessary ), it also maintains the advantages of using constructor and prototype at the same time. In other words, you can check whether an existing method is valid to determine whether to initialize the prototype.
[Note] when using the dynamic prototype mode, you cannot use the object literal to override the prototype. If the prototype is rewritten when an instance has been created, the connection between the existing instance and the new instance is cut off.

Function Person (name, age, job) {// attribute 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 ("Nicolas", 29, "Software Engineer"); friend. sayName ();

[8] parasitic constructor mode: Creates a function that encapsulates the code of the created 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",29,"Software Engineer");friend.sayName();//"Nicholas"

[Parasitic constructor mode application] creates a special array with additional methods. Because the Array constructor cannot be directly modified, this mode can be used.

Function SpecialArray () {// create an Array var values = new Array (); // Add the value values. push. apply (values, arguments); // Add the values method. toPipedString = function () {return this. join ('|') ;}; // return array return values;} var colors = new SpecialArray ("red", "blue", "green"); alert (colors. toPipedString (); // "red | blue | green"

[9] Secure constructor mode: the so-called secure object indicates that there is no public attribute, and its method does not reference this object. Secure objects are best suited to some security environments (this and new are not allowed in these environments) or to prevent data from being changed by other applications.

Function Person (name, age, job) {// create the Object var o = new Object () to be returned; // you can define private variables and functions here // Add method o. sayName = function () {alert (name) ;}; // return object return o ;}// except for the sayName () method, no other method is available to access the name value var friend = Person ("Nicolas", 29, "Software Engineer"); friend. sayName (); // "Nicolas"

The preceding nine methods are used to create objects in javascript. I hope they will be helpful for your learning.

Articles you may be interested in:
  • Js uses objects to directly create object code
  • Create objects in JS (several common methods)
  • Create an object using JavaScript
  • Three methods for creating objects in JavaScript
  • Summary of several common methods for creating objects in js (recommended)
  • Javascript Functions, object creation, encapsulation, attributes and methods, and inheritance
  • Learn Javascript object-oriented from Interview Questions (create object)
  • How to create an object using JavaScript
  • Examples of how to create objects in js

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.