JavaScript Object creation: Method overview and best practices

Source: Internet
Author: User
Creating objects in JavaScript is a complex topic. This language provides many ways to create objects. New users and veterans may feel confused about this and do not know which one to choose. No...



Creating objects in JavaScript is a complex topic. This language provides many ways to create objects. New users and veterans may feel confused about this and do not know which one to choose. However, although there are many ways to create objects, it seems that the syntax is quite different, but they may actually have more similarity than you do. This article will take you on a journey of organizing object creation methods to reveal the dependency and progressive relationship between different methods.

Object literal

Our first stop is undoubtedly the simplest way to create an object, the object literal volume. JavaScript always promotes the ability to create objects "out of nothing"-without classes, templates, and prototypes-with "nothing, an object with methods and data will appear.

var o = {  x: 42,  y: 3.14,  f: function() {},  g: function() {}};

But this method has one drawback: if we want to create an object of the same type elsewhere, we have to copy and paste the method, data, and initialization of this object. We need a method to create objects of the same type in batches, instead of creating only one object.

Factory Functions

Our next stop is the factory function. Obviously, it is easiest to use this method to create a class of objects with the same structure, interfaces, and implementations. Instead of directly creating an object literal, we use the object literal as the return value of the function. When we need to create objects of the same type multiple times or multiple times, we only need to call this function.

function thing() {  return {    x: 42,    y: 3.14,    f: function() {},    g: function() {}  };}var o = thing();

But this method also has a disadvantage: it will lead to memory expansion, because each object contains an independent copy of the factory function. Theoretically, we want all objects to share a copy of the factory function.

Prototype chain

JavaScript provides a built-in mechanism for sharing data between objects, called prototype chain. When we access the attributes of an object, it delegates some other objects to complete this request. We can use this to modify the factory function so that each object created by it only contains its own unique data, requests for other attributes are all delegated to a common object in the prototype chain.

var thingPrototype = {  f: function() {},  g: function() {}};function thing() {  var o = Object.create(thingPrototype);  o.x = 42;  o.y = 3.14;  return o;}var o = thing();

In fact, JavaScript itself has a built-in mechanism to support this general mode. We do not need to create this common object (prototype object) by ourselves. JavaScript will automatically create a prototype object for each function. We can put the shared data directly in this object.

thing.prototype.f = function() {};thing.prototype.g = function() {};function thing() {  var o = Object.create(thing.prototype);  o.x = 42;  o.y = 3.14;  return o;}var o = thing();

But this method also has a disadvantage: it will lead to repetition. The first and last rows of the above thing functions are repeated in each "factory function of the delegated prototype", with almost no difference.

ES5 categories

We can extract the repeated code and put it into a UDF. This function creates an object and establishes a delegate (inheritance) Relationship with the prototype of any other function (Parameter Function). Then, we take the newly created object as a parameter, call this function (Parameter Function) and return the new object.

function create(fn) {  var o = Object.create(fn.prototype);  fn.call(o);  return o;}// ...Thing.prototype.f = function() {};Thing.prototype.g = function() {};function Thing() {  this.x = 42;  this.y = 3.14;}var o = create(Thing);

In fact, JavaScript also has a built-in support mechanism for this method. The create FUNCTION we define is actually a basic Implementation of the new Keyword, so we can replace create with new by hand.

Thing.prototype.f = function() {};Thing.prototype.g = function() {};function Thing() {  this.x = 42;  this.y = 3.14;}var o = new Thing();

This website we are arriving at is generally called the ES5 class. It creates an object through a function, delegates the data to be shared to the prototype object, and uses the new Keyword to process repeated logic.

However, this method also has a disadvantage: It is lengthy and ugly, and it will be more lengthy and ugly when implementing inheritance.

ES6 categories

The latest improvements to JavaScript are ES6. It is much simpler to use the new syntax to implement the above functions.

class Thing {  constructor() {    this.x = 42;    this.y = 3.14;  }  f() {}  g() {}}var o = new Thing();
Comparison

For many years, the relationship between JavaScript developers and the prototype chain has always been imminent and unclear. Today, we are most likely to encounter two ways to create objects. One is the class syntax that strongly depends on the prototype chain, and the other is the factory function syntax that completely does not depend on the prototype chain. These two methods have different performance and characteristics-although the difference is not big.

Performance

Today, the JavaScript engine has been greatly optimized, making it difficult to infer how it will be faster through JavaScript code. The key lies in the measurement method. However, measurement methods sometimes fail. Usually every six weeks, there will be an updated JavaScript Engine release, and the measurement method adopted earlier and the decision made based on this measurement method may be meaningless. Therefore, my rule of thumb is to select the most official and widely used syntax, because most of the time it goes through the most practical tests, so the performance is the highest. Currently, the class syntax best fits this point. When I write this article, the class syntax is about three times faster than the factory function that returns the literal.

Features

With the release of ES6, the differences between classes and factory functions disappear. Currently, both factory functions and classes can implement real private data-factory functions are implemented through closures and classes are implemented through WeakMap. Both implement multi-inheritance-factory functions can mix other attributes into their own objects, classes can also mix other attributes into their own prototypes, or through class factories, can also be achieved through proxies. Factory functions and classes can also return any object as needed, and the syntax is also very simple.

Conclusion

In general, I prefer the class syntax. It is standard, simple, clean, and fast, and provides all features that were available only to function factories.

The above is the JavaScript creation object: Method overview and best practices. For more information, see PHP Chinese website (www.php1.cn )!

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.