Ecmascript5 strict JSON mode more

Source: Internet
Author: User
Tags javascript array
ArticleDirectory
    • Strict Mode)
    • JSON

Since its launch, the ecmascript5 specification has had a significant impact on the development of JavaScript. This article is a blog post I translated from John resig (author of jquery ).

Ecmascript 5 strict mode, JSON, and more

Previously, I analyzed es5's object and attribute systems. This is a highlight of the language.

We also need to pay attention to many other new features and APIs. The main features are strict mode and native JSON support ).

Strict Mode)

Strict mode is a new feature in es5, which allows you to execute yourCode. A strict environment will prevent certain code behaviors and throw more exceptions (more information and standard code are provided to users in general ).

After es5 is compatible with ES3, all features that can be used normally in ES3, but the "not recommended" feature in es5 will expire in strict mode (or throw an exception ).

The strict mode will promote code specifications in the following ways:

    • Capture common code vulnerabilities and throw exceptions

    • When some relatively "insecure" code is executed, it is blocked or thrown an exception (for example, obtaining global object access)

    • Disable confusing or unconsidered features

Most information about the strict mode can be found on es5 specification [PDF] page 223.

It should be noted that the strict mode of es5 is different from the strict mode provided by Firefox (Javascript. Options. Strict can be started through about: config ). Es5 focuses on potential errors in coding specifications. (The strict mode of Firefox only emphasizes some best practices ).

How do I start the strict mode?

Very simple. Add "use strict" before your code to enable strict mode for all your code:

 
"Use strict ";

Or only in one execution context, such:

 
Function imstrict () {"use strict"; //... your code ...}

Look, the syntax for starting the strict mode can no longer be simple, just a statement "use strict. There is no new syntax, no complicated configuration is required, and there is no side effect on the old browser.

Es5 does not add or modify the language syntax. Therefore, you can perform an elegant downgrade in the old browser.

Define a strict mode in a function. You can define your own JavaScript library without affecting external code.

 
// Non-strict code... (function () {"use strict"; // define your library strictly ...}) (); // non-strict code...

Currently, many libraries use this package technology (including the entire library package in an automatically executed anonymous function ).

So what happens when you place the script in strict mode? Many things

Variables and attributes

Try to assign Foo = 'bar'; If 'foo' is not defined in advance, it will fail. Prior to this, Foo will be assigned a value, and Foo will be used as the window. Foo attribute of the Global Object window. Now this will throw an exception. Make sure to avoid some annoying bugs.

Perform write operations on any property with the writable attribute being false, and delete the property with the attribute being false, extensible attribute) an error is returned when you add properties to an object that is false. Traditionally, errors will not be thrown when you try these actions, but will quietly fail.

Deleting a variable, a function, and a parameter will cause an error.

 
VaR Foo = "test"; function test () {} Delete Foo; // errordelete test; // errorfunction Test2 (ARG) {Delete ARG; // error}

Defining an attribute of the same name more than once in a literal object causes an exception to be thrown.

 
// Error {FOO: True, foo: false}
Eval

Almost any attempt to use the 'eval' name is forbidden.

// All generate errors... OBJ. EVAL =... OBJ. foo = eval; var EVAL = ...; for (VAR eval in ...) {} function eval () {} function test (eval) {} function (eval) {} new function ("eval ")

In addition, the new variables introduced through eval are invalid.

 
Eval ("Var A = false;"); print (typeof A); // undefined
Functions

An error occurs when you try to override the arguments object:

 
Arguments = [...]; // now allowed

Defining parameters with the same name will cause an error: function (Foo, foo)

Access to arguments. Caller and arguments. callee throws an exception. Therefore, any anonymous function you want to reference should be given a name, such:

 
SetTimeout (function later () {// do stuff... setTimeout (later, 1000) ;}, 1000 );

The arguments and caller attributes of other functions do not exist, and the ability to define them is disabled:

Function Test () {function inner () {// don't exist, eithertest. Arguments =...; // errorinner. Caller =...; // error }}

The last long-plagued (and annoying) Bug has been fixed: null or undefined is forcibly converted to a global object in the following example. The strict mode prevents such events and throws an exception.

 
(Function () {...}). Call (null); // exception
With

The with statement is completely killed in the strict mode. In fact, its appearance may be used as a syntax error.

Es5 strict mode varies with code changes. It would be interesting to observe how developers begin to adopt these specifications and how they change Javascript development.

JSON

The second major feature of ecmascript is the native support for JSON.

I have supported this promotion for a long time, and now I am very happy to see that it has been written into specifications.

There are two main methods for processing JSON: JSON. parse (converting a JSON string into a JavaScript Object) and JSON. stringify (converting a javascript object into a serialized string ).

JSON. parse (text)

Converts a serialized JSON string into a JavaScript Object.

VaR OBJ = JSON. parse ('{"name": "John"}'); // prints 'john' print (obj. Name );
JSON. parse (text, translate)

Use a conversion function to convert or remove the value.

 
Function translate (Key, value) {If (Key = "name") {return value + "resig" ;}} var OBJ = JSON. parse ('{"name": "John", "last": "resig"}', translate); // prints 'John resig' print (obj. name); // undefinedprint (obj. last );
JSON. stringify (OBJ)

Convert an object into a serialized JSON string

 
VaR STR = JSON. stringify ({name: "John"}); // prints {"name": "John"} print (STR );
JSON. stringify (OBJ, ["white", "list"])

Only serialize the specified attribute of the whitelist

 
VaR list = ["name"]; var STR = JSON. stringify ({name: "John", last: "resig"}, list); // prints {"name": "John"} print (STR );
JSON. stringify (OBJ, translate)

Serialize objects using conversion functions

 
Function translate (Key, value) {If (Key = "name") {return value + "resig" ;}} var STR = JSON. stringify ({"name": "John", "last": "resig"}, translate); // prints {"name ": "John resig"} print (STR );
JSON. stringify (OBJ, null, 2)

Add a specified number of spaces to the output.

 
VaR STR = JSON. stringify ({name: "John"}, null, 2); // prints // {// "name": "John" //} print (STR );
JSON. stringify (OBJ, null, "\ t ")

Use specific characters for Separation

 
VaR STR = JSON. stringify ({name: "John"}, null, "\ t"); // prints: // {\ n \ t "name ": "John" \ n} print (STR );

In addition, some basic types have added new general methods. However, they are not interesting to be blunt. The results from string, Boolean, and number are the same as those from valueof (), and date is the same as that from toisostring ()

// Yawnstring. Prototype. tojsonboolean. Prototype. tojsonnumber. Prototype. tojsondate. Prototype. tojson
. BIND ()

The introduction of the built-in BIND () method is very popular. It can change the execution environment of a function (almost equivalent to the BIND implementation in prototype framework)

 
Function. Prototype. BIND (thisarg, arg1, arg2 ...)

Make this keyword of the function point to a specific object and input any parameters you want to specify.

 
VaR OBJ = {method: function (name) {This. Name = Name; }}; setTimeout (obj. method. BIND (OBJ, "John"), 100 );
Date

First, if the given value is in ISO format, the date constructor will try to parse the date and then process other input accepted by it.

 
VaR date = new date ("2009-05-21t16: 06: 05.000z"); // prints 2009-05-21t16: 06: 05.000 zprint (date. toisostring ());

In addition, the date object now has a new toisostring () method to output the date in ISO format.

. Trim ()

A native, built-in trim () method is supported by string objects. It features the same as the trim method we implemented, but the native efficiency is higher.

Array

Javascript array extensions include indexof, lastindexof, every, some, foreach, MAP, filter, reduce, and reduceright.

Another new method, array. isarray, is included and provides the same functions as the following code:

 
Array. isarray = function (array) {return object. Prototype. tostring. Call (array) = "[object array]";}

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.