Ecmascript5 new javascript API entry

Source: Internet
Author: User
Tags tojson

Ecmascript5 provides a series of new API interfaces, which are supported in most of the new browsers, including ie9, chrome, and firfor, A small number of APIs are not supported by all browsers. The following content only describes most of the supported APIs. With the new API, we can design very reliable classes and maintain the original JavaScript style.

Ecmascript 5.1 (or es5 only) is the latest revision of the ecmascript (JavaScript-based specification) standard. Similar to HTML5 standard processes, es5 standardizes existing Javascript methods by adding statements and native ecmascript objects. The following browsers can support the behavior of ecmascript5: Opera 11.60 +,
Internet Explorer 9 +, Firefox 4 +, Safari 5.1 +, and chrome 13.
Currently, ie9 does not support rigorous models, but ie10 does.

To check whether your browser is compatible with ecmascript5, you can view the ecmascript 5 compatibility table, and observe the compatibility of other browsers. Alas, the hard-pressed front-end programmers, CSS, and JS scripts have compatibility issues and are speechless.

Object. Create (prototype, descriptors)

Creates an object based on the specified prototype and sets the object attributes (optional ).

function Poker(style, title, value) {    this.Style = style;    this.Title = title;    this.Value = value;}var pokerA = Object.create(new Poker("club", "A", 14));alert(Poker.constructor); //function Function() { [native code] }alert(new Poker().constructor); //function Poker(style, title, value) {                                //            this.Style = style;                                //            this.Title = title;                                //            this.Value = value;                                //        }alert(Poker.constructor.prototype); //function Empty() {}alert(Poker.prototype == new Poker().constructor.prototype); // truealert(Poker.constructor.prototype == new Poker().constructor.prototype); // falsealert(new Poker().propertye); //undefinedalert(Poker.prototype == pokerA.constructor.prototype); //truealert(Poker.constructor.prototype == pokerA.constructor.prototype); // falsealert(new Poker("club", "A", 14).Value); //14alert(pokerA.Value); //14

The code above writes a bunch of logical expressions, which proves that there is no difference in the results between the objects constructed using object. Create and the objects constructed using constructors. The advantage of using object. Create is that the prototype chain is clean. on the Internet, the following solutions are provided for Browsers without object. Create. The following code not only describes the technical knowledge of object. Create, but also supports the earlier version of IE to implement a clean prototype.

if (typeof Object.create !== 'function') {    Object.create = function(o) {        function F() { }        F.prototype = o;        return new F();    };}function Poker(style, title, value) {    this.Style = style;    this.Title = title;    this.Value = value;}var pokerA = Object.create(new Poker("club", "A", 14));alert(Poker.constructor); //function Function() { [native code] }alert(new Poker().constructor); //function Poker(style, title, value) {                                //            this.Style = style;                                //            this.Title = title;                                //            this.Value = value;                                //        }alert(Poker.constructor.prototype); //function Empty() {}alert(Poker.prototype == new Poker().constructor.prototype); // truealert(Poker.constructor.prototype == new Poker().constructor.prototype); // falsealert(new Poker().propertye); //undefinedalert(Poker.prototype == pokerA.constructor.prototype); //truealert(Poker.constructor.prototype == pokerA.constructor.prototype); // falsealert(new Poker("club", "A", 14).Value); //14alert(pokerA.Value); //14

Object. defineproperty (object, propertyname, descriptor)

Set rich value control for a property of the specified object

Object. defineproperties (object, descriptors)

Provides rich value control for a set of attributes of a specified object

Function setpokerstate (poker, provalue) {If (arguments [0] instanceof poker) {object. defineproperty (arguments [0], // sets an attribute "state" for an object, // The attribute name is a string {// a group of modifier objects value: provalue, // The default value is undefined writable: True, // whether the value is read-only. The default value is false enumerable: false. // whether the value can be enumerated. The default value is false retriable: true // whether the attribute can be modified to delete the default value false})} var pokera = object. create (new poker ("club", "A", 14); setpokerstate (pokera, 5); alert (pokera. state );

If we need to assign more values or values, we can specify the set and get functions. However, set/get cannot be used together with value and writable.

Function setpokerstate (poker, provalue) {If (arguments [0] instanceof poker) {object. defineproperty (arguments [0], // set an attribute "state" for an object, // The attribute name is a string {// a group of modifier objects enumerable: false, // whether the value can be enumerated defaults to false retriable: True, // whether the attribute can be changed to delete the default false set: function (x) {This. state = x <= 5? X: 5;}, get: function () {return this. state; }})} var pokera = object. create (new poker ("club", "A", 14); pokera. state = 10;

If you need to set multiple attributes, see the following code for demonstration.

Object. defineproperties (pokera, {"backgroundimg": {value: "Images \ common \ hide.png", enumerable: false, // It is not allowed to traverse writable: false // read-only }, "forgroundimg": {value: "Images \ spade \ k.png", enumerable: false, // it cannot be used to traverse writable: false // read-only}, image: {get: function () {return this. state = 0? This. backgroundimg: This. forgroundimg;}, enumerable: true }});

To understand which attributes of an object are defined, you can use the following APIs:

Object. getownpropertydescriptor (object, propertyname)
Definition of returned attributes
Object. getownpropertynames (object)
Returns the names of all properties, even if they cannot be enumerated.

Below is a demo

alert(Object.getOwnPropertyNames(PokerA).length); //4var names = Object.getOwnPropertyNames(PokerA);for (var i = 0; i < names.length; i++) {    alert(names[i] + "\n" +    Object.getOwnPropertyDescriptor(PokerA, names[i])    );}

It can be agreed that the object cannot be extended, but the attribute value can be changed or deleted.

Object. preventextensions (object)
Prevent new attributes from being added to objects
Object. isextensible (object)
Can attributes be added to an object?

alert(Object.isExtensible(PokerA)); //trueObject.preventExtensions(PokerA);alert(Object.isExtensible(PokerA)); //false

You can use the following APIs to implement more strict control.

Object. Seal (object)
Attributes cannot be added or deleted.
Object. issealed (object)

alert(Object.isSealed(PokerA)); //trueObject.seal(PokerA);alert(Object.isSealed(PokerA)); //false

If you want to strictly seal the object, you can

Object. Freeze (object)
Prevent modification of existing attributes and attribute values, and prevent addition of new features.
Object. isfrozen (object)

Finally, if you want to obtain the object prototype, you can use

Object. getprototypeof (object)

The object is similar to the above. Then, let's take a look at some static members of ecmascript5 extension on other objects.

Array. isarray
What do you mean?

alert(Array.isArray([])); //truealert(Array.isArray({})); //false

Array. indexof

Array. lastindexof

It's a good thing. Don't explain it.

alert(["Hello", "javaScript", "ECMAScript", "HTML5"].indexOf("javaScript"));//1alert(["Hello", "javaScript", "ECMAScript", "HTML5"].lastIndexOf("javaScript"));//1

Array. Every

Perform a callback condition check on each element of the array to check whether any element that does not meet the conditions exists. All

var arr1 = "Charles,Mark,Bill,Vincent,William,Joseph".split(",");alert(arr1.every(                function(item, index) {                    return item.length < 5;                }                )                ); //falsealert(arr1.every(                function(item, index) {                    return item.length < 10;                }                )                )//true

Array. Some

Is used to determine whether the array has any elements that meet the conditions, similar to the any

var arr1 = "Charles,Mark,Bill,Vincent,William,Joseph".split(",");alert(arr1.some(                function(item, index) {                    return item.length < 5;                }                )                ); //truealert(arr1.some(                function(item, index) {                    return item.length < 10;                }                )                )//true

You can use

Array. foreach

var arr1 = "Charles,Mark,Bill,Vincent,William,Joseph".split(",");arr1.forEach(function(item, index) {    if (index % 2 == 0) {        arr1[index] = "name:" + item;    }});arr1.forEach(function(item, index) {    alert(item);});

In fact, foreach is best to process the value directly. If you want to change the array, it is best to use

Array. Map

var arr1 = "Charles,Mark,Bill,Vincent,William,Joseph".split(",");var arr2 = arr1.map(function(item, index) {    if (item.indexOf("ll") > -1) {        return item;    }});arr2.forEach(function(item, index) {    alert(item);});

To filter the array, you can use

Array. Filter

var arr1 = "Charles,Mark,Bill,Vincent,William,Joseph".split(",");var arr2 = arr1.filter(function(item, index) {    if (item.indexOf("ll") > -1) {        return true;    }});arr2.forEach(function(item, index) {    alert(item);});

You can use

Array. Reduce

var arr1 = "Charles,Mark,Bill,Vincent,William,Joseph".split(",");var arr2 = arr1.reduce(function(item, next) {    return item + "][" + next;});alert("[" + arr2 + "]");//[Charles][Mark][Bill][Vincent][William][Joseph]

There is also a reverse Processing

Array. reduceright

var arr1 = "Charles,Mark,Bill,Vincent,William,Joseph".split(",");var arr2 = arr1.reduceRight(function(item, next) {    return item + "][" + next;});alert("[" + arr2 + "]"); //[Joseph][William][Vincent][Bill][Mark][Charles]

Now Array Processing is close to that of LINQ !!!

Date (). tojson ()

From a glance, the built-in architecture is refreshing.

alert(new Date().toJSON());alert(new Date(2012, 11, 12).toJSON()); //2012-12-11T16:00:00.000Z

The string is given a trim. You are late.

alert("[" + "   Hello ".trim() + "]"); //[Hello]

In general, the new API is still very powerful.

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.