37-way Web front-end development questions JavaScript Chapter!

Source: Internet
Author: User
Tags exception handling function definition object object

    1. Ajax, cross-domain, JSONP

Reference: JavaScript Advanced Programming Chapter 21st: AJAX operations in Ajax and Comet jquery

    1. Usage and differences for apply and call:

Usage:

Can inherit the methods and properties of another object, except that the argument list is different

Difference:

Function.apply (obj, args) args is an array, passed as a parameter to function

Function.call (obj, arg1, arg2,...) arg* is a parameter list

Apply a magical use: You can convert an array by default to a list of parameters

For a chestnut: there is an array of arr to push into a new array, and if you use call you need to remove the elements from the array and push again, and apply only Array.prototype.push.apply (this, arr)

    1. Compatibility of the BIND function

Usage:

The bind () function creates a new function, which is a binding function. When this binding function is called, the binding function invokes the original function as the first parameter of the Bind method when it is created, the second and subsequent arguments to the Bind method, and the parameters of the binding function itself as arguments to the original function in order.

A binding function can also use the new operator to create an object: This behavior is like using the original function as a constructor. The supplied this value is ignored, while the parameter at the time of invocation is supplied to the impersonation function.

    1. Explain the event proxy

Event delegation takes advantage of event bubbling, specifying only one event handler to manage all events of a certain type.

Example: HTML section: To click on Li to eject its ID

HTML section

<ul id= "List" >

<li id= "Li-1" >li 2</li>

<li id= "Li-2" >li 3</li>

<li id= "li-3" >li 4</li>

<li id= "li-4" >li 5</li>

<li id= "li-5" >li 6</li>

<li id= "li-6" >li 7</li>

</ul>

JS section

document.getElementById ("list"). AddHandler ("click", Function (e) {

var e = e | | window.event;

var target = E.target | | E.srcelement;

if (target.nodeName.toUpperCase = = "LI") {

Console.log ("List item", E,target.id, "was clicked!");

}

});

    1. Explain how this works in JS.

This is mainly used by the following five scenarios in JavaScript.

As a function call, this binds the global object, and the browser Environment Global object is window.

The This of the intrinsic function of the inner function also binds the global object, which should be bound to the object corresponding to its outer function, which is a bug of JavaScript, replaced with that.

Used as a constructor, this binds to the newly created object.

Used as an object method, this binds to the object.

Calling this with apply or call will be explicitly set to the first parameter of a function call.

    1. Inherited

Reference: JS How to implement inheritance?

    1. AMD vs. CommonJS?

AMD is dependent on pre-loading

CMD is dependent on delayed loading

    1. What is a hash table?

A hash table (hash table, also known as a hash list) is a data structure that is accessed directly from a key value. That is, it accesses records by mapping key code values to a location in the table to speed up lookups. This mapping function is called a hash function, and the array that holds the record is called the hash table.

There are two steps to using a hash lookup:

Use the hash function to convert the lookup key to an array index. In an ideal situation, different keys are converted to different index values, but in some cases we need to handle the case where multiple keys are hashed to the same index value.

So the second step of the hash lookup is to handle the conflict. Handles a hash collision conflict. There are many ways to deal with hash collision collisions, such as zipper and linear detection methods.

The method that the element feature transforms the subscript is the hash method. The hashing method is of course more than one, the following list three kinds of more commonly used:

1, Division Hash method

The most intuitive one, using this hashing method, the formula: index = value% 16

learned that the assembly is known that the modulus is actually obtained through a division operation, so called "division hashing method."

2, Square hash method

The index is very frequent operation, and the multiplication operation is more time-saving than division (for the current CPU, it is estimated that we do not feel it), so we consider dividing the division into multiplication and a displacement operation. Formula: Index = (value * value) >> 28 (Shift right, divided by 2^28. Notation: Shift left to large, is multiply. Right shift to small, is except. )

This method can get good results if the values are evenly distributed, but the values of the individual elements of the graph I drew above are 0--very unsuccessful. Perhaps you have a question, if value is large, value * value does not overflow? The answer is yes, but our multiplication does not care about overflow, because we are not at all to get the multiplication result, but to get index.

3, Fibonacci (Fibonacci) hash method

Ways to resolve conflicts:

    1. Zipper method

Each element of an array of size m points to a linked list, and each node in the list stores the hash value as the key value pair for that index, which is the zipper method.

The hash implementation using the Zipper method is divided into two steps, the first is to find the linked list of one should according to the hash value, and then find the corresponding key along the chain list order.

    1. Linear detection method:

Resolve collision conflicts using empty spaces in arrays

Reference: Talking about algorithms and data structures: 11 How hash tables work

    1. What is a closure package? What is the effect of closures?

Closures are functions that have access to variables in another function scope. The common way to create closures is to create another function inside one function.

Role:

Anonymous self-executing functions (function () {...}) (); An anonymous function is created and executed immediately, because the external cannot reference its internal variables, so it will be released soon after execution, the key is that this mechanism does not pollute the global object.

Cache, which preserves values inside the function

Implementing encapsulation

Implementing a template

Reference: Use of JS closures

    1. Pseudo-Arrays:

What is a pseudo-array:

A pseudo-array is an object with the length property that can be converted to a real array by Array.prototype.slice

such as arguments objects, as well as calls to Getelementsbytagname,document.childnodes, they all return nodelist objects are pseudo-arrays

We can turn a pseudo-array into a true array object by Array.prototype.slice.call (Fakearray): Returns a new array without modifying the original array

Reference: Pseudo-arrays

    1. The difference between undefined and null, as well as undeclared:

Null means there are no objects, that is, this value should not be available here. Typical usage:

(1) As a function parameter, the parameter of the function is not an object.

(2) As the end point of the object prototype chain.

(3) null can be used as a null pointer. As long as the value that is intended to hold the object does not actually hold the object, the object should be explicitly saved with a null value.

Undefined indicates that a value is missing, meaning there should be a value here, but not yet defined.

(1) The variable is declared, but when it is not assigned, it is equal to undefined.

(2) when calling a function, the argument that should be supplied is not provided, which equals undefined.

(3) The object does not have an assigned property, and the value of this property is undefined.

(4) When the function does not return a value, undefined is returned by default.

Undeclared is the contaminated name, access to the variable that is not declared, an exception is thrown, and execution is terminated. That undeclared is a syntax error

Reference: The difference between undefined and null

    1. Event bubbling mechanism:

Propagates from the target element to the top-level element. On the way, if a node is bound to a corresponding event handler, these functions are triggered at once. If you want to block event blistering, you can use E.stoppropagation () (Firefox) or e.cancelbubble=true (IE) to organize the bubbling propagation of events.

    1. Explain why the next piece of code is not iife (immediately called function expression): function foo () {} ();?

The function definition (the statement starts with the function keyword) cannot be executed immediately, which will undoubtedly result in a syntax error (SYNTAXERROR). When the function definition code snippet is wrapped in parentheses, the parser can recognize it as a function expression and then call it. Iife: (function foo () {}) ()

Distinguish (function () {}) (); and (function () {} ()); In fact, the two achieve the same effect.

function literal: Declare a Function object first, and then execute it. (function () {alert (1);}) ();

Precedence expression: Because the JavaScript execution expression is from inside the parentheses to the outside, you can enforce the declared function with parentheses. (function () {alert (2);} ());

    1. What is the difference between "attribute" and "property"?

The attribute and property of DOM elements are different things. Attribute translated as "attributes", property translated as "attribute".

attribute is an attribute node, each DOM element has a corresponding attributes attribute to hold all attribute nodes, attributes is a container for an array of classes, and the exact point is Namenodemap, Methods that do not inherit from Array.prototype and cannot call the array directly. Each numeric index of the attributes holds a attribute node in the form of a name-value pair (name= "value"). <div class= "box" id= "box" gameid= "880" >hello</div>

A property is an attribute that, if viewed as a normal object object, is a property that is stored in object as a name-value pair (name= "value"). It is similar to adding and removing property and normal objects.

Many attribute nodes also have a corresponding property attribute, such as the ID of the DIV element above and the class is both attribute, and there is a counterpart, which can be accessed and modified regardless of which method is used.

In summary, the attribute node is visible in the HTML code, and the property is just an ordinary name-value pair attribute.

    1. Please indicate the difference between document load and document ready two events.

The difference between Document.ready and onload--javascript the document load completion event. There are two kinds of events for page load completion:

One is ready, indicating that the document structure is loaded (not including non-text media files such as pictures)

The second is onload, which indicates that all elements, including pictures and other files, are loaded and completed.

The $ (function () {}) in jquery; his role or meaning is that the DOM can be manipulated after the DOM has been loaded. In general, the first page response load order is, domain name resolution-loading html-loading JS and css-loading pictures and other information.

    1. What is use strict? What are the pros and cons?

Add "use strict" at the beginning of all functions (or all outermost functions); command to start strict mode.

"Strict Mode" has two methods of calling

1) put "use strict" in the first line of the script file, the entire script will run in "strict mode". If the line statement is not in the first row, it is not valid and the entire script runs in normal mode. This requires special attention if the code files of different schemas are merged into one file.

2) Place the entire script file in an anonymous function that executes immediately.

Benefits

    • Eliminate some unreasonable and unreasonable JavaScript grammar, reduce some strange behavior;

    • To eliminate some of the unsafe code operation, to ensure the security of code operation;

    • Improve compiler efficiency, increase running speed;

    • Pave the future for new versions of JavaScript.

Harm

The same code, in "Strict mode", may have different running results; some statements that can be run under normal mode will not work in strict mode

    1. What parts of the browser-side JS include?

Core (ECMAScript), Document Object Model (DOM), Browser object model (BOM)

    1. What objects are included in the DOM?

The DOM is an API (application programming Interface) for HTML and XML documents. The DOM depicts a hierarchical tree of nodes that allows developers to add, remove, and modify portions of a page.

Common DOM Methods:

getElementById (ID)

getElementsByTagName ()

AppendChild (node)

RemoveChild (node)

ReplaceChild ()

Insertchild ()

CreateElement ()

createTextNode ()

GetAttribute ()

SetAttribute ()

Common DOM Properties

The text value of the InnerHTML node (element)

Parent node of the ParentNode node (element)

ChildNodes

Attributes node (element) attribute node

Reference: HTML DOM methods

    1. What are the basic types of JS?

Undefined, Null, Boolean, number, String

object is a complex data type, which is essentially composed of a set of unordered name-value pairs.

    1. What is the difference between a base type and a reference type?

The basic type is shown in the previous question. Reference types are: Object, Array, Date, REGEXP, Function

Store

The base type value occupies a fixed amount of space in memory and is therefore stored in the stack memory

The value of a reference type is an object that is saved in heap memory. A variable that contains a reference type actually contains not the object itself, but a pointer to the object being changed

Copy

Copying a base type value from one variable to another creates a copy of the value

Copying the value of a reference type from one variable to another is actually a pointer, so two variables end up pointing to the same object

Detection type

Determine which base type a value is available with the typeof operator,

The instanceof operator is used to determine which reference type a value is

    1. Garbage collection routines about JS

JS is a programming language with an automatic garbage collection mechanism, and developers don't have to worry about memory allocation and recycling.

Values that leave the scope are automatically marked as recyclable and therefore will be deleted during garbage collection

"Tag Cleanup" is currently the mainstream garbage collection algorithm, the idea is to add tags to the currently unused values, and then reclaim their memory

Another garbage collection algorithm is a "reference count", the idea of which is to track the number of times all values are referenced. The JS engine is no longer using this algorithm, but when accessing non-native JS objects (such as DOM elements) in IE, this algorithm can still cause problems

The reference count algorithm causes problems when there is a circular reference in the code

Removing a reference to a variable not only helps eliminate circular references, but also benefits garbage collection. To ensure that memory is effectively reclaimed, the global objects that are no longer used, global object properties, and references to circular reference variables should be released in a timely manner

    1. ES5, in addition to functions, what can produce scopes?

Try-catch and with extended scopes. Because they all create a new variable object.

Both statements add a variable object to the front of the scope chain. For the WITH statement, the specified object is added to the scope chain. For a catch statement, a new variable object is created that contains the declaration of the thrown error object.

When an error occurs in a try code block, the execution jumps to the catch statement, and then pushes the exception object into a Mutable object and puts it in the scope's head. Inside a catch code block, all local variables of the function are placed in the second scope chain object. Note that once the Catch statement finishes executing, the scope chain opportunity returns to the previous state. Try-catch statements are useful in code debugging and exception handling, so it is not recommended to avoid them altogether. You can reduce the performance impact of catch statements by optimizing your code. A good pattern is to delegate the error to a function handler

With (object) {statement}. It means to add an object to the top of the scope chain

Code Snippets

function BuildUrl () {

var qs = "Debug=true";

With receives the location object, so its variable object contains all the properties and methods of the Location object, and this variable object is added to the front end of the scope chain

With (location) {

The href here is actually location.href. A variable named URL is created as part of the function execution environment

var url = href + qs;

}

return URL;

}

Reference: JS try, catch, finally statement and with statement JavaScript Development Advanced: Understanding JavaScript scopes and scope chains

    1. JS has several function call mode?

Method call Model var obj = {func:function () {};} obj.func ()

function call mode var func = function () {} func ();

constructor invocation Pattern

Apply/call Call pattern

    1. Describe the event model? What is the event model of IE? What is an event agent? How does the event agent locate the target of the actual event?

Capture---in target--bubble, ie should be only bubbling without capture.

Event proxies are handled by binding events on the parent element, and are positioned by the target of the event object.

    1. What are the implementation methods of JS animation?

Using Timers settimeout and SetInterval

    1. What else is the way to implement animation?

JS Animation:

Using Timers settimeout and SetInterval

Css:transition, animation

Transition contains 4 properties: Transition-delaytransition-durationtransition-propertytransition-timing-function, 4 properties for the animation: delay , duration, corresponding CSS properties and easing functions,

Transform Contains 7 properties: Animation-nameanimation-durationanimation-timing-functionanimation-delayanimation-directionanimation-iteration-cou Ntanimation-fill-modeanimation-play-state, they can define animation name, duration, easing function, animation delay, animation direction, repetition count, fill mode.

HTML5 Animation

Canvas

Svg

Webgl

Reference: A simple comparison of front-end animation effect implementations

    1. What are the characteristics of object-oriented?

Encapsulation, inheritance, polymorphism

    1. How do I tell if a property is from its own object or a prototype chain?

Hasownprototype

    1. ES6 new Features

1) arrow operator Inputs=>outputs: The left side of the operator is the input parameter, and the right side is the action to be taken and the value returned

2) Support class, introduced the Class keyword. The class provided by ES6 is actually the wrapper for JS prototype mode

3) Enhanced object literals.

    1. The prototype can be defined in the object literal proto: XXX//Set its prototype to XXX, equivalent to inheriting xxx

    2. Definition methods can be used without the function keyword

    3. Calling the parent class method directly

4) string Template: ES6 is allowed in the use of anti-quotes ' to create a string, which can be created in a string containing the dollar sign with curly braces wrapped variable ${vraible}.

5) Automatically parse the values in the array or object. For example, if a function returns multiple values, it is common practice to return an object that returns each value as a property of the object. In ES6, however, by using the Deconstruction feature, you can return an array directly, and the values in the array are automatically parsed into the corresponding variable that receives the value.

6) Default parameter value: You can now specify the default value of the parameter when defining the function, instead of using the logic or operator to achieve the purpose as before.

7) An indeterminate parameter is an unnamed parameter that receives an indefinite number of parameters at the same time using a named parameter in the function. In the previous JavaScript code, we can do this by arguments variables. The format of an indeterminate parameter is a three period followed by a variable name that represents all the indeterminate arguments. For example, in this case, ... x represents the arguments for all incoming add functions.

8) The extension parameter is another form of syntactic sugar, which allows the transfer of arrays or arrays of classes directly as parameters of a function without using apply.

9) Let and Const keywords: You can think of a as Var, except that the variable it defines is scoped to a specific range to be used, and leaving this range is not valid. Const is intuitive to define constants, which are variables that cannot be changed.

The for value iterates through each loop that it provides is not an ordinal but a value.

) Iterator, generator

12) Module

Map, Set, Weakmap, WeakSet

Proxy can listen to what is happening on the object and perform some corresponding actions after these things happen. All of a sudden, we have a strong ability to track an object, but also useful in data binding.

Symbols symbol is generated by calling the symbol function, which receives an optional name parameter, and the symbol returned by the function is unique. You can then use this return value as the key for the object. Symbol can also be used to create private properties that cannot be directly accessed by the value of a property that is made a key by symbol.

New API for Math, number, String, object

Promises is a pattern for handling asynchronous operations

Reference: ES6 new features Overview

    1. How to get a DOM node, how nodes traverse

Get node: getElementById () getElementsByTagName ()

Node traversal: 5 Methods of first-order traversal of the DOM tree

    1. How do I add a browser prefix to some properties with less?

You can customize a function

Code Snippets

. Border-radius (@values) {

-webkit-border-radius: @values;

-moz-border-radius: @values;

Border-radius: @values;

}

div {

. Border-radius (10px);

}

    1. How is JS asynchronous mode implemented?

Reference: Promise mode for JavaScript asynchronous programming

    1. The implementation of the picture pre-loading

Pre-load plug-ins with jquery pictures lazy load

1. Load jquery, with Jquery.lazyload.js

2. Set the placeholder for the picture as data-original, giving the picture a special label, such as class= ". Lazy"

3. Then delay loading: $ (' Img.lazy '). Lazyload (); This function can select some parameters:

3.1. Image preload Distance: threshold, by setting this value to load when the picture does not appear at the top of the viewable area.

3.2. How the event binding loads: Event

3.3. The picture is confined to a container: container

Use JS to implement the image loading: is a new picture object, binding the OnLoad function, assigning a value URL

Using CSS to achieve pre-loading of pictures

Write a CSS style to set a batch of background images and then hide them

Improved: Use JS to postpone preload time and prevent loading with other content on the page

Using Ajax for pre-loading

is to request a picture address via Ajax request. You can also load css,js files in this way, etc.

    1. If two click events are bound on the same element, one is executed during the capture phase, and one is performed in the bubbling phase. How many events are executed when the click condition is triggered? What is the order of execution?

I said in answer to this question is two events, first execute the capture after the execution bubbling. Actually, it's not right.

The events bound on the target element are executed in the order in which they are bound!!!!

That is, the events that are bound to the clicked element occur in code order, and other elements are bubbling or capturing "perceived" events, which, according to the criteria of the standard, capture the event and then a bubbling event occurs. The order of all events is: Other elements capture phase events--This element code order event--and other element bubbling phase events.

Reference: javascript-Parent-child DOM simultaneously binds two click events, one with capture, one with bubble execution order

    1. How do I implement block-level scopes in JS?

Using anonymous functions (execute functions immediately)

(function () {...}) ()

Using ES6

Block-level scopes introduce two new forms of declaration that you can use to define a variable or constant that exists only in a block of statements. The two new declaration keywords are:

Let: The syntax is very similar to Var, but the defined variable exists only in the current statement block

Const: Similar to let, but declares a read-only constant

Using let instead of Var makes it easier to define a local variable that exists only in a block of statements, without worrying about conflicts with variables of the same name in other parts of the function body. Variables declared with Var inside a let statement are no different from variables declared with VAR outside the Let statement, They all have function scopes, not block-level scopes.

    1. What is the difference between defining function and using Prototype.func in constructors?

    2. Call function directly, each instance of the class will copy the functions, the disadvantage is to waste memory (as above). The prototype method defines the way that functions are not copied into each instance, and all instances share the definition in prototype, saving memory.

    3. But if the prototype property is an object, all instances will also share an object (this is what the function should not do), and if one of the instances changes the value of the object, the value of all instances will be changed. In the same way, if a function called by prototype is used, the method of all instances changes as soon as it is changed. --You cannot use the prototype property on an instance, only for classes and functions.

    4. The deep cloning of JS implementation object

Because the data type in JS is divided into basic data types (number, string, Boolean, null, undefined) and reference type values (objects, arrays, functions). These two types of objects are very different when replicating clones. The original type stores the actual data of the object, and the object type stores the object's reference address (the actual contents of the object are stored separately, in order to reduce the data overhead usually in memory). In addition, the object's prototype is a reference object that puts the properties and methods of the prototype in memory and points to the memory address in the form of a prototype chain.

Clones are then divided into two categories:

Superficial cloning:

The original type is a value pass, and the object type is still a reference pass

Deep cloning:

All elements or attributes are completely copied, completely detached from the original object, meaning that all modifications to the new object are not reflected in the original object

Deep Clone implementations:

Code Snippets

function Clone (obj) {

if (typeof (obj) = = ' object ') {

var result = obj instanceof Array? [] : {};

for (var i in obj) {

var attr = obj[i];

Result[i] = Arguments.callee (attr);

}

return result;

} else {

return obj;

}

};

Reference: Deep cloning of objects in JavaScript deeply cloned JavaScript

37-way Web front-end development questions JavaScript Chapter!

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.