Home PC Games Linux Windows Database Network Programming Server Mobile  
  Home \ Programming \ JavaScript object - Flexible and dangerous     - top command causes the system load increases (Linux)

- Computer black magic: tail recursion (Programming)

- Function Getting the Linux shell (Programming)

- MySQL Tutorial: Using tpcc-mysql pressure measurement (Database)

- Linux operating system log system (Linux)

- Windows7 system using Vagrant to build Linux virtualized development environment (Linux)

- Linux text processing tool of awk (Linux)

- C ++ multithreading and critical resource instance (Programming)

- RHEL5.x RHEL6.x replace CentOS yum source (Linux)

- Windows Desktop use VNC remote connect Linux (Linux)

- JEdit 5.2 Pro Edition installation on Ubuntu 14.04 (Linux)

- Vi syntax highlighting settings (Linux)

- Java inheritance initialization problem (Programming)

- Five Linux user space debugging tool (Linux)

- Node.js simple interface server (Server)

- How to view the Linux QPS (Linux)

- Smack 4.1.x Upgrade Guide (Linux)

- Ubuntu 15.10 15.04 14.10 14.04 Install Ubuntu Tweak (Linux)

- HAProxy performance under high concurrency (Server)

- Installation and management of Linux applications (Linux)

  JavaScript object - Flexible and dangerous
  Add Date : 2018-11-21      
  No kind of data structure is simpler than the object of JavaScript flexible. As a weak dynamically typed languages, JavaScript object's properties without any constraint, the result of that is, when in use so cool, what would like to add properties directly coupled with the herd, there is no limit or template class, I want to read what properties directly "point" out on the line, write it is quite simple; however, when this code runs it ......

JavaScript This flexibility of the biggest problems is no constraint. For example, a shop system has two parts, one to generate the order object, another part of the object to get orders display. Let dry naturally behind the front-end programmers to show that part of the thing, for example, to show orders inside commodity prices on the page, will fall order.product.price.sum. However, write part of the code which generates orders buddy child is not necessarily reliable, in order to have a gift that is not price, price is no field altogether, or adjust the front end order.product.price.sum, too, js code execution to which even dead , behind Han also get out. Even more frightening is that many systems now introduced a node, the front end of the separation boundary moved back part of it, this time calling order.product.price.sum on the node, too, get out the entire page.

Is not that very low in this case? Your company already provides a good estimate of the order data in the product price field there will be, even if I did not price the rear end of Big Brother will give you a pass {}. Moreover, people with the rear end of the java, strongly statically typed language, various properties already defined, Zeneng lost it? Besides the front of the line to be tested for so long, how can online out of this problem?

Now JSON is already flying between network standard data structure, even if the back-end system you are using java to write, call this tip to write the backend interface obtained or JSON. But this is JSON turn it from what? You must expect a certain kind of object it? Unbearable. Perhaps as early as the back-end brother found Java too rigid, in order to fit the flexible JSON, with a map of the early people. Moreover, even if the rear end honest with class, if your shop system is large, there are several different types of shop orders, these orders are not afraid of it comes from the same class, the field is inevitable that there are differences, you can guarantee you development team to complete the document properties you can master all like it?

Anyway, we are not so full of documents, even if sometimes a little document, the backend will be well-intentioned brother told me: the Code shall prevail!

If you want to put this on the line before missing fields bug all measured out, I think too hard on QA brothers, back-end data are not they call the shots, Paul missing on the line long after the sudden really give less Diansha.

People always do not fly, you have to think of a way from the code.

The most direct way is to carefully every step: at risk every call to a property when they are judged at the parent node exists. This judgment carefully to what extent we should try to estimate the degree of reliable data sources. Total for the previous example, an order where they would not even trade it did not, so the code could look like this:
var showPrice
if (order.product.price)
  showPrice = order.product.price

The reality is often more complex, for example, I now want to get the phone number of the order data is a product manufacturer contact information inside the first one, and I do not trust backend interface, even the order has no products can not be guaranteed, then ......
var temp, temp1, temp2, temp3, phone;
if ((temp = order.product)! = null) {
  if ((temp1 = temp.seller)! = null) {
    if ((temp2 = temp1.contact)! = null) {
      if ((temp3 = temp2.phone)! = null) {
        phone = temp3 [0];

So clumsy! JS so if you want to write back and I'd rather do the backend to write Java!

I coffeescript. In fact, we are doing the project and not built on top of coffee, but I used coffee, how to use is another topic, anyway, with the coffee, this code is this:
phone = order.product? .seller? .contact? .phone? [0]

Unfortunately, I am somewhat obsessive-compulsive disorder who, when I see so many question marks will think that a bunch if compiled, I feel for the computer tired. Besides this question mark it is easy to miss, quietly and less difficult to find a question mark. Anyway, I think I will only be in front of the property may be missing a question mark.

In fact, do these judgments do nothing more than a property once the call chain missing direct return undefined. js itself does not provide this stuff, himself a package.
Object.prototype.getAttr = function (path) {
  attrLink = path.split ( '.');
  var ref = this [attrLink [0]];
  for (var i = 1; i     if (ref)
      ref = ref [attrLink [i]];
      return undefined;
  return ref;

So it would access properties like this:
order.getAttr ( 'product.seller.contact.phone.0')

So safe. But when debugging I would rather have to explain abnormal red Used tell me who in the end is not defined or is empty quiet Mimi did not want to get an undefined value. Answer is affirmative, the above code in the output log ref is empty on the line. The last question is getAttr method is not brute force method to get the properties, unlike Java, as long as the private property can only be used getter. Let alone ensure that other small partners must use this method to take property, even I might have read, read directly on the spot. Ultimately, the Object.getAttr way I never used in the actual development.

Feeling that in front of a question mark inside cofee approach is enough, if we ourselves feel this property have to have the back-end interfaces are not passed that too that Han had. But the truth is that everything is possible, this also can not blame the rear end of Big Brother, chances are that the order data is sent over from other systems or very old wonderful data.

Ye trouble? My principle is to minimize the loss as much as possible, that is, the code range Anomalies reduced to a minimum. It is up to try..catch.

Try to look at the case where the code, the total can not catch what try what. But still some laws.

Those who do not fly our own data should not be written, but from the external interface, data interfaces use this code there is definitely a certain range, at least this situation is to try some of the. It is too rough. Look at the data in the characteristics of a large number of external data is often iterative, for example, will display a list of orders on the order list will certainly be a cycle, then the cycle for internal try it, this is at most an order can not be displayed. There is no local data where there is a unified process, for example, I do use handlebars node project template, will use a lot of custom helper, the helper for most of the data into the displayed results, such as price format What. Compare Coincidentally these helper has a uniform code entry:
helpers = _.extend (
    require ( './ helper1'),
    require ( './ helper2'),
    require ( './ helper3')
// "_" Is the underscore or lodash

In fact, that is, the individual files helpers integrate into a large object, then:
module.exports = _.reduce (helpers, function (memo, f, k) {
    memo [k] = function () {
        try {
            return f.apply (this, arguments)
        } Catch (e) {
            console.error ( 'handlebars helper error', e)
            return ''
    return memo
}, {})

Before export all the helper functions are wrapped in a try ... catch in. This has a helper in the field are also missing error will cause a little something not show.

In fact, I put all the helper into one large object whose original intention was not for this, but since the files are registered every helper again looks to repeat too much, feel uncomfortable. There is not a well-known principle of code maintenance is probably saying "any duplicate code should avoid" do? This look out the benefits.

It seems to look perfect, but also not. Later, a man child wrote a helper, I did not put these helpers inside, but registered in other files go alone, and the results of data really wonderful there, really hard to detect to the tragedy staged. . .

Well, in the final analysis with various sorts of clever but useless also arrived, but not outlaw the cards. In fact, I really want to end all comrades around the data format ordained, and strictly enforced.
- Samhain: Powerful intrusion detection system under Linux (Linux)
- Thinking in Java study notes - Access modifiers (Programming)
- Linux user login ban (Linux)
- Linux package manager - yum (Linux)
- Linux uses the SMTP proxy to send mail (Linux)
- Use FirewallD build dynamic firewall (Linux)
- SHELL script to use anti SSH brute force and vsftpd (Linux)
- The three-way division of the sorting algorithm Quicksort (Programming)
- Security basics: simple analytical framework for Linux system firewall (Linux)
- HDFS Distributed File System Resource Manager Developer summary (Server)
- Installation and configuration under Linux SVN server - Backup - Recovery - Scheduled Tasks (Server)
- HDFS Hadoop Distributed File System Works (Server)
- HTTP and FTP TCP-FLOOD CC Attacks Analysis and Prevention solutions under CentOS 6.5 (Linux)
- 3 tips Linux command (Linux)
- Python2 ---- function using dictionaries (Programming)
- Linux process management related content (Linux)
- C ++ function object (Programming)
- OpenSUSE / Linux network configuration (Linux)
- Shell generated using automated configuration script Orabbix (Database)
- Linux5.8 installed phpMyAdmin was unable to issue related php-mcrypt (Database)
  CopyRight 2002-2022 newfreesoft.com, All Rights Reserved.