The language of JavaScript learning notes

Source: Internet
Author: User
Tags hasownproperty

A. In usage
    1. For...in

      Enumerates all enumerable properties of an object

    2. Detecting Dom/bom Properties

      if ("onclick" in Elem) {    //element supports Onclick}if ("onerror" in window) {    //window supports onerror}
    3. Detecting the prototype attributes of a JS object (combined with the hasOwnProperty () function)

      if ("attr" in obj &&!obj.hasownproperty ("attr")) {    //obj has prototype properties attr}

      Note: The prototype attribute is masked out by the instance property of the same name, so it cannot be detected:

      function Super () {    this.attr = 1;} function Sub () {    this.attr = 2;} Sub.prototype = new Super (), var obj = new Sub (), Alert (("attr" in obj &&!obj.hasownproperty ("attr"));  False
Two. | | Operators and && operators
    • || Can be used to populate default values, such as:

      var obj = {};obj.name = "";  Note that JS has a bunch of fake values: +0,-0, 0, NaN, null, Undefined, "", "", Falsevar name = Obj.name | | "Ayqy"; alert (name);

      P.S. The person thinks this thing is not good, unless it can be determined that the original property value cannot be any kind of false value, otherwise the default value will overwrite the original value

    • && can be used to prevent TypeError from reading attributes from undefined values, for example:

      var obj = {};//var attr = obj.obj.attr;   Error, TypeError, cannot read attribute var from undefined value attr = obj.obj && obj.obj.attr; Only if obj.obj exists and is not a false value will it be taken attr

      P.S. Personal opinion is similar to &&, it is better to use if detection, not only can show clearer logic flow, but also easy to add more detection conditions

P.S. These two usages are described in the first part of the book, and may be more biased towards presentation of language features, not recommended usage

personal advice not to use this , of course, see this code to understand its role and vulnerability

Three. Reduce global variable pollution
    1. With "namespaces", or empty objects, the essence is to reduce the creation of global variables to 1, such as Yui's Y object, jquery jquery and the $ object. For example:

      var app = {};   Namespace: Appapp. Consts = {    //child namespace: Constant    URL: {        //double namespace: url    }}app. Modules = {    //Child namespace: module}app. data = {    ///Sub-namespace: Date}
    2. With Iife (anonymous function immediately executes), the essence does not create global variables at all, 0 pollution

      (function () {    //Module1}) ();(function () {    //Module2}) ();

      But the disadvantage is obvious, unable to implement the object cache and sharing, out of the closure will be gone

Therefore, the general practice is to combine namespaces and Iife, the whole with namespaces organized, in the module within the appropriate place with Iife

Four. 4 Modes of invocation
    • Method invocation Pattern: Obj.fun (), or obj["fun"] ();

    • Function call Pattern: Fun (), this point points to the global object

    • constructor invocation mode: New Fun (); prototype of the object points to the fun Prototype,this point to the new object

    • Apply Call Mode: Fun.apply (this, Arrargs);

Five. About Arguments objects

The arguments object is not an array object, nor does it support all array methods , just a somewhat special ordinary object, particularly in its Length property (dynamic Update)

The following tests can be done:

function Fun () {    var x = Object.prototype.toString.call (arguments);    alert (x);    var arr = [];    Alert (Object.prototype.toString.call (arr));}; Fun ();//Ie8:[object Object] and [object Array],chrome:[object Arguments] and [object array]//don't matter, it's not an Array anyway.

a little trick : You can use the slice method to convert an arguments object to an array, for example:

function Fun () {    //arguments.sort ();   Error, does not support the sort () function    var arr = Array.prototype.slice.call (arguments);    Convert    arr.sort ();//No error, description conversion successful    alert (arr);}; Fun (3, 2);  2, 3

Note: only slice has this effect, concat is not, although the slice and the non-parametric concat are used in the same way as the array (all copied one copy)

Six. How cascading (chained calls) are implemented

A function that does not return a value returns this, so it supports chained calls, such as those in jquery:

$ ("#adBlock"). Removeclass ("active"). Hide ();
Seven. Improper constructor call can cause scope pollution

If you do not use the new operator, call the constructor directly, such as fun (), and this point points to the global property, which is the Window object under the browser environment, which may contaminate the world scope

Eight. Simplify the formal parameter list to a single object

For example:

function Fun (height, width, margin, padding) {   //parameter too long, order cannot be remembered    //do something}/* * @param {number} arg.height Height * @ param {Number} arg.width width  * @param {number} arg.margin White * @param {number} arg.padding filler */function fun (ARG) {  Do not remember the parameter order    //Do something}

The benefits are as follows:

    1. The interface becomes more user-friendly when the parameter sequence is not cared for

    2. You can just pass in a JSON object.

Cons: Write a bunch of notes explaining exactly what parameters are needed because it's completely invisible through an arg

Nine. Anti-Counterfeiting object (persistent object)

The properties of the security object can be replaced or deleted, but the integrity of the object is not compromised

Also known as persistent objects, a persistent object is a collection of simple function functions

P.S. The concept of anti-counterfeiting objects appears in the [functional] part of the book, and currently does not fully understand the meaning of the function to be expressed, to enrich themselves and then see

10. Arrays

The essence is the key-value pair, which is the object, so there is no advantage in accessing speed

The difference is that Array.prototype provides a number of array manipulation functions, plus a special length property

Note: 1. The actual memory space occupied by the array

var arr = [1];arr[99] = 100;

At this point, arr points to a value that does not occupy 100 elements of space because the result above is equivalent to:

var arr = {    "0": 1,    "99": 100};

    1. The Length property is writable

      You can use arr.length = n; Delete all elements of >= n

    2. Common use of the length property

      How to save the counter: arr[arr.length] = value;

      or simpler: Arr.push (value);

    3. Array type detection

      Because typeof arr returns "Object" and the instanceof operator fails when it crosses a frame, it is not easy to detect array types

      The book gives a super-troublesome way:

      function IsArray (value) {    return value &&        typeof value = = = "Object" &&        typeof value.length = = = "Number" &&        typeof value.splice = = = "function" &&        ! ( Value.propertyisenumerable ("Length"));}

      In fact, there are simple ways that the author has not yet appeared when he wrote the book:

      can be used Object.prototype.toString.call (value) = = = ' [Object array/function ...] ' To do type checking, or to distinguish between native objects and custom objects, such as:

      [Object JSON]   Native JSON object [Object Object]//Custom JSON object

      For more information on type detection, please see the Breeze: JS Learning note 11_ Advanced tips

11. Regular Expressions

JS Regular expression function is not complete, but basic enough, such as only support 3 modes: g/i/m ~ Global mode/Ignore case mode/multiline mode

and the support of special meta-characters (\d, \s and the like) is also relatively small, but fortunately support for non-capturing grouping and regular look around, is still very good

So using regular expressions in JS requires more testing and more information about regular expressions see the Breeze: Regular Expression Learning notes

There is one less common point : The properties of the RegExp object

    • Global: Is the G mode open?

    • IgnoreCase: Returns whether I mode is on or off

    • LastIndex: Returns the starting position of the next exec match

    • Multiline: Returns whether multiline mode is open

    • Source: Returns the regular expression string

It is important to note that regexp objects created by literal means may refer to the same instance, for example:

var regex1 =/abc/g;var Regex2 =/abc/g;var str = "AAA\R\NABC\R\NAAA"; alert ([Regex1.lastindex, Regex2.lastindex]);    0, 0regex1.test (str); alert ([Regex1.lastindex, Regex2.lastindex]);    8, 0alert (regex1 = = = Regex2);   False

The last two rows of the old browser output 8, 8 and true, it is said that the regular literal sharing instance is ES3, the native test found IE8 no problem, but theoretically IE6 there is this problem (IE6, ES5 not out)

Twelve. Native object manipulation functions

P.s. Here only points needing special attention, complete various operation functions please see the Breeze: JS Learning Notes 1_ basics and common sense

1. Array manipulation functions
    1. Arr1.push (ARR2); arr2 is inserted as a single element , for example:

      var arr1 = [1];var arr2 = [2, 3];arr1.push (ARR2); alert (arr1[2]); Undefinedalert (arr1[1][1]);  3
    2. Arr.shift () is much slower than arr.pop () because deleting the first element requires updating the index of all the elements, and deleting the trailing element does not require

    3. Arr.unshift (), inserts an element at the head of the array, IE6 returns undefined, which should return the length of the new array

2. Object manipulation functions

Obj.hasownproperty ("hasOwnProperty") returns false

3. Regular Expression object manipulation functions

The regex.exec (str) function is the most powerful and, of course, the slowest execution speed

Regex.test (str) simplest, fastest, note : Do not open G mode because it is purely wasteful (test only returns match/mismatch, one scan is enough)

4. String manipulation functions
    • Str.replace (regex, fun); a function that can be used to match the target part with a regex, and can be used to further process the matching part.

      Special Note : If the regex does not open G mode, then only the first matching part is replaced, not the full string substitution

    • Str.replace (regex, replacement), the $ in the replacement section has a special meaning:

      • $$: Represents $ If the replacement part has $ to be escaped

      • $&: Represents the entire matched text

      • $n: For example, $, $, $ ... represents the captured text

      • $ ': Indicates text that precedes the matching part

      • $ ': Indicates text that is after the matching part

      For more detailed examples, see the W3school:javascript replace () method

    • Str.split (regex); There is a special case that requires particular attention :

      var str = "A & B & C";    & is the delimiter var arr = Str.split (/\s* (&) \s*/);   Contains the capture var arr2 = Str.split (/\s*&\s*/);    does not contain capture var arr3 = Str.split (/\s* (?:&) \s*/);    Contains non-capture alert (arr); [A, &, b, &, C]alert (ARR2);    [A, B, C]alert (ARR3);    [A, B, c]

      If you accidentally use a regular expression with a captured grouping, the result may be different than expected

13. dross

P.S. Here is not intended to copy the contents of the book, only to give the author's consent to the worst place

    • Automatically inserts a semicolon. Really bad, like a typical ASI error:

      function Fun () {    return    {        attr:1;    }} Alert (Fun (). attr);  Typeerror:cannot Read property ' attr ' of undefined
    • typeof Bad use, this is a design mistake, historical reasons

    • Paseint () and octal. a very subtle mistake :

      var year = "n"; var month = "n"; var day = "the"; Alert (parseint (year));  ie8:2015 Chrome:2015alert (parseint (month)); ie8:0    Chrome:8alert (parseint (day));   ie8:0    Chrome:9

      Since the value starting with 0 is considered to be octal, omitting the second argument parseint () will parse 08/09 as an octal, so the result is 0.

      Processing time date is too easy to cause parsing errors, so it is best not to omit the second parameter of parseint ()

      P.s.chrome is normal, perhaps an ES version of parseint () has been modified, Chrome has been implemented. So the dross does not always exist, of course, is not the dross also depends on how programmers use.

    • Unicode. JS support for Unicode is not good, although it is a historical reason, but not support is not supported

      P. S. JS When Unicode itself did not expect to have 1 million characters, JS character is 16 bits, can correspond to the first 65,536 Unicode characters, and Unicode in order to expand, the rest of each character is represented by a pair of characters, but JS will be such a character as two characters, so.

14. Chicken Ribs

P.s. Ibid., only the author agrees

    • Continue performance is low. can be eliminated if

    • Low bit operation performance . (none of the other books mention it) because to toss: double

    • Whether new should be used or not. If you use it, you may contaminate the scope

    • The void operator. The monocular operation, which returns undefined, can be used to implement Iife, for example:

      void function () {    //Do something} ();

      The author suggests not to use void because no one knows what it does.

xv. Json

The first number of integers cannot be 0, Douglas (the Master of the invention JSON) himself said, the value can be integer, real or scientific count, but the first cannot be 0, in order to avoid octal ambiguity

Resources:
    • The essence of JavaScript language

The language of JavaScript learning notes

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.