The front face of questions and answers (a)

## front end

** a. Understanding of the closure and which closure where used, and the closure drawbacks **

```javascript
<button id="add">加1</button>
<span id="span">10</span>
(function(){
var a = 10;
add.onclick = function (){
a++;
span.innerHTML = a;
}
})()
```

** II. For cross-domain understanding it, jsonp limit **

Q: Why do cross-domain
A: cross-domain, under normal circumstances is not to say normal communication in the following two domain name is not passed, or is unable to obtain additional domain data below, the main reason is that the browser to consider security issues, using the same-origin policy restrictions by JS browser to prevent malicious users to obtain illegal data.

Q: Same Origin Policy
A: limiting how to interact with resources from another source from a source document or script loaded. This is a critical security mechanism for isolating potentially malicious files.

Q: "homologous"
A: same protocol, the same name, the same port

The purpose of the same-origin policy: Q
A: in order to ensure the security of user information to prevent malicious sites to steal data.

Q: homologous to limit the scope of
A: Cookie, LocalStorage IndexDB and can not be read; the DOM can not be obtained; AJAX request can not be transmitted

Solution ** **
JSONP
1. GET request without support only supports POST HTTP requests and other types (although the use of post + iframe dynamically generated object is to achieve cross-domain POST, but this is a rather extreme way, not recommended). Clearly stated: jquery POST request is used jsonp may be due to the success of jquery POST automatically converted into GET, actual or GET request
2. General get requests to complete all the features. Such as: If the request can be linked to other parameters in the parameter domain server transmits (be careful not to hang private data), i.e. <script src = "http: //xxx/getPerson.php name = Hello & age = 18?"> </ Script >
3. JSONP easy to implement, but also there are some security risks, if the third party is free to execute the script, then it may tamper with the contents of the page, intercept sensitive data.
4. transfer data in both the trusted, JSONP is a very appropriate choice.
The general cross-domain JSONP can be seen for acquiring data in other domains.
6. General method for cross-domain can be used up to a cross-domain JSONP JSONP achieved, which is used in the front end.

the window.name
. 1, must be used in conjunction with iframe
2, window.name transmission technology, originally restricted Thomas Frank some disadvantages for solving the cookie (4 x 20 Kb per domain, and only the data string, set and retrieve cookie grammatical complexity, etc.) and invention. Later, Kris Zyp on the basis of this method of strengthening the window.name transmission, to solve cross-domain data transmission problems.
The beauty of 3.window.name: name value still exists in the different pages (or even different domain) is loaded, and can support very long name value (2MB).
Features:
1. browser window has window.name property. The most important feature of this property is, whether or not homologous, as long as in the same window, a front page this attribute is set, after a web page can read it.
2. That in a window (window) of the life cycle, the window to load all the pages are sharing a window.name each page of window.name have read and write permissions, window.name is persistent a window had loaded all the pages, and new pages will not load and reset.

Rationale:
1. When you open a page in a browser, or add an iframe in the page, a window object is created corresponding, when the page loads when another new page, name the properties window will not change of.
2. This will add a dynamic iframe src page and then load the data page, assigned to window.name in the data page will need.
3. At this time, however, the index page of the carrier iframe (i.e. the requested page data) is not directly accessible, not in the same domain name attribute of the iframe, then only need to reload iframe a blank page and the page carrying the same domain, data can be read on window.name

document.domain cross-domain
this is the realization of ideas with similar cross-domain cookie, is set document.domain value in two related domain name, and then let the two values are equal, so that you can achieve cross-domain operation

cross-domain cookie

Cross-domain postMessage


** three .. browser which uses asynchronous place **

First, determine JS is a scripting language, his executive order is executed line by line from top to bottom, only a browser javascript engine, so the browser colleagues can only perform one task, then what principle to achieve asynchronous operation is it?
Browser javascript engine really is single-threaded, but the browser itself is multi-threaded, browser contains
*** javascript engine thread, the thread rendering interface, browser events to trigger thread, Http request thread ***
So starting asynchronous operation when there will be a separate thread to do the operation, javascript engine thread will not be blocked, still continue to resolve js code.


** four, CSS elastic layout, which places used before **

flex layout


** five, uncertain how to achieve a high level width and centered vertically **
1. The simplest layout flex
the display: flex;
The justify-Content: Center;
align = left-items: Center;
2. using table-cell
outer container
display: table -cell;
text-align = left: Center;
Vertical-align = left: Middle;
internal elements
Vertical-align = left: Middle;
the display: inline-Block;
3. use CSS3 transform
outer container
display: relative
elements within
transform: translate (-50%, % -50);
position: Absolute;
Top: 50%;
left: 50%;

** six, and let const difference, can change the properties of an object const defined it **

let const and are valid only in the block-level action is declared within the domain.
let: No variable lift (not yet reached the let declarations, the variable is not accessible)
const: no variable lift, a basic type declaration for the time constant can not be modified; declared objects can be modified
const arr = {name: 'Small Lovely ', Age: '21'}
arr.name = 'XuanXuan'
the console.log (arr)
because the object is a reference type, is stored only arr pointer to the object, which means, const pointer occurs only ensure change, modify the properties of the object does not change
the object pointer, it is allowed. That is the definition of const reference type as long as the pointer does not change, regardless of other changes are allowed.


** seven, ES6 used before you, what's new, what, what you use **
define variables joined let const
arrow function
Array.from () will convert the array object class can traverse the object array
class class

** Eight arrow function, a function of the characteristics of an arrow, pointing ** this
arrow anonymous function is a function, not bound own this, arguments, super, new.target
arrow function will capture their value in this context, as their own of this value, when using the call / apply binding, the equivalent of just passed in the parameter, it has no effect on this

** IX to array weight **
for ES6: Array.from (the Set new new (ARR));
`` `JavaScript
<Script type =" text / JavaScript ">
the let ARR = [ '. 1', 2,1, 3, 5,6,5]
the let arrString = arr.toString ()
the console.log (arrString)
arrSplit arr1.split = ( ',') dividing a // string into a string array.
// join () of all elements in the array into a string.
the console.log (arrSplit)
the let new new SET = the Set (arrSplit)
the console.log (SET)
the let newArr = Array.from (SET)
the console.log (newArr)
</ Script>
`` `

** ten, which means change original array **

the Shift: delete the first element and returns remove elements, namely the empty undefined
unshift: add elements to the beginning of an array and returns the new length
pop: Removes the last element and returns the deleted
push: add to the end of the array element, and returns the new length
reverse: reverse order of the array
sort: sorting an array
splice: splice (start, length, item) delete, add, replace the array element, returns the deleted array, does not return without deleting


** Eleven, deep and shallow copy copy **
shallow copy: the original object reference or the original array directly assigned to the new object, a new array, the new object / array is just a reference to the original object of
deep copy: create a new object and arrays, the original "value" attribute of the object (all the elements of the array) copied, the "value" rather than the "reference"

Deep copy of the degree requirements
* we use a deep copy, be sure to find out the extent of our requirements for deep copy: only "deep" copy object properties or array elements of the first level, or recursively copy all levels of object properties and array elements? *

*** array deep copy (copy only the first stage array element) ***
1. Direct traversal
2. Slice ()
Slice () method returns a new array element portion taken from the existing fragment consisting of the array (not ! change the original array)
usage: array. slice (start, end) start is the index showing the starting elements, end represents the termination element index
when slice () when not any parameters, return a default length and the same original array new array

` JavaScript
var Array = [. 1, 2,. 3,. 4];
var copyArray Array.slice = ();
copyArray [0] = 100;
the console.log (Array); // [. 1, 2,. 3,. 4]
Console. log (copyArray); // [100, 2,. 3,. 4]
`` `
3. the concat ()
` `` JavaScript
var Array = [. 1, 2,. 3,. 4];
var copyArray Array.concat = ();
copyArray [0] = 100;
the console.log (Array); // [. 1, 2,. 3,. 4]
the console.log (copyArray); // [100, 2,. 3,. 4]
`` `
*** *** deep copy target
1 directly traverse
Object.assign 2.ES6 of

JavaScript `` `
var obj = {
name: 'I'm drunk cream',
Job: 'front-end development'
}
var copyObj = Object.assign ({}, obj);
copyObj.name = 'I'm drunk cream No. 2';
Console. log (obj); // {name : " cream drunk forest", job: "development distal"}
the console.log (copyObj); // {name: "I'm drunk cream No. 2", job: "development distal"}
`` `
Object.assign: for merging the object, the source object (source) of all enumerated attribute, copied to the target object (target), and returns the target combined
usage: Object.assign (target, source1, Source2); therefore copyObj = Object.assign ({}, obj ); this code will be the one attribute of obj are copied to the {}, then returned assign copyObj
3.ES6 extended operator:
extended operator (...) for all parameters extracted through both the attributes of the object, copy of the current in the object
** of nested objects, unfortunately, the above three methods, will fail: **

JavaScript `` `
var obj = {
name: {
firstName: 'drunk',
lastName: 'I'm cream'
},
Job: 'front-end development'
}

var copyObj = Object.assign ({}, obj)
copyObj.name.lastName = 'I'm drunk cream';
the console.log (obj.name.lastName); // cream Lin drunk
console.log (copyObj.name.lastName); // cream Lin drunk
`
*** *** copy all levels

1. The only copy of the first level, but also be able to copy the values in the array or object at all levels
2. not alone against an array or object, but can be common to arrays, objects and other forms of complex JSON objects
below this trick can be described as "a fresh recruit, eat days"

(. 1) .JSON.parse (the JSON.stringify (XXXX))
`` `JavaScript
var Array = [
{Number:. 1},
{Number: 2},
{Number:. 3}
];
var = copyArray the JSON.parse (the JSON.stringify (Array))
copyArray [0] .number = 100;
the console.log (Array); // [{Number:. 1}, {Number: 2}, {Number: }. 3]
the console.log (copyArray); // [{Number: 100}, {Number: 2}, {Number:. 3}]
`` `
2. manually written recursively

```javascript
var array = [
{ number: 1 },
{ number: 2 },
{ number: 3 }
];
function copy (obj) {
var newobj = obj.constructor === Array ? [] : {};
if(typeof obj !== 'object'){
return;
}
for(var i in obj){
newobj[i] = typeof obj[i] === 'object' ?
copy(obj[i]) : obj[i];
}
return newobj
}
var copyArray = copy(array)
copyArray[0].number = 100;
console.log(array); // [{number: 1}, { number: 2 }, { number: 3 }]
console.log(copyArray); // [{number: 100}, { number: 2 }, { number: 3 }]

```
***存在大量深拷贝需求的代码——immutable提供的解决方案***

In fact, even if we know how to make a deep copy in all cases, we are still facing some problems: a deep copy is actually very consumption performance. (We may just want to change a new array of one of the elements of time does not affect the original array, but was forced to put the entire original array are copied again, this is not a waste it?) So, when your project has a lot of deep copy needs time, performance may form a bottleneck constraints of.

immutable role:

Through a set of API immutable introduced to achieve:

1. changing new array (target) when not changing the original array (Object)

2. In a large number of deep copy operation is significantly reduced consumption performance

```javascript
const { Map } = require('immutable')
const map1 = Map({ a: 1, b: 2, c: 3 })
const map2 = map1.set('b', 50)
map1.get('b') // 2
map2.get('b') // 50
```

Twelve, call () and apply () and the difference between the role?

Difference: apply () and call () action makes no difference, usage and call () method is slightly different, is to call () The second parameter (function call parameters used), is passed one by one; and apply ( ) a second parameter value is used in the form of an array of incoming
role: in Javascript, each function comprising two non-inherited methods comes, Call and apply. The use of these two methods are called function domain specific action, this object is substantially equal to the set value of the function body.

apply method accepts two parameters, the first parameter is a scope in which the function is running, the second is an array of parameters or arguments object.
Method call method and apply the same effect, the first parameter is the same, except that, the rest of the parameters need to be listed individually.

apply (thisArg, argArray);
call (thisArg [, arg1, arg2 ...]);

use or apply call depends on the specific situation. If you know all the small number of parameters or parameters, you can use call;
not sure if the number of parameters, or a large number, or you receive an array of arguments or a target, you need apply.
Thirteen, localStorage sessionStorage Cookie
thing in common: both are stored in the browser, and homologous.
Different points:
WebStorage is stored locally on the client, storage, and including localStorage sessionStorage.

** localStorage **: localStorage life cycle is permanent, which means that unless the user is displayed on the UI to clear localStorage information provided by the browser, otherwise this information will always be there. Stored data size is generally 5MB, but it is only in the client (ie browser) to save, and does not participate in the communication server.

** sessionStorage **: sessionStorage valid only in the current session, close the browser page or after removal. Stored data size is generally 5MB, but it is only in the client (ie browser) to save, and does not participate in the communication server. Primal interface may be acceptable, the package may again have a better support for Object and Array.

Using the same API use *** localStorage and sessionStorage: ***

localStorage.setItem ( "key", "value "); // to "key" a name of a stored value "value"
localStorage.getItem ( "key"); // Get the name "key" value
localStorage.removeItem ( "key"); // delete the name "key" information.
localStorage.clear (); // Clear all the information localStorage

Scope different:
different browsers can not share information or sessionStorage in localStorage. Between different pages of the same browser you can share the same localStorage (page belonging to the same domain name and port), but between different pages or tabs sessionStorage of information can not be shared. It should be noted that the tab page and refers only to top-level window, if a tab contains multiple homologous iframe tag and they belong to a page, so they can be shared between the sessionStorage.

** Cookie **
lifetime is only valid until the cookie expiration time set, even if the window or browser is closed. Storing data about the size of 4K. There are number of limitations (different for each browser). Communicate with the server side: every time carried in the HTTP header, if you use a cookie to save too much data can cause performance problems. Cookie-encapsulation requires the programmer, the Primal Cookie interfaces unfriendly.


```javascript
//Cookie方法
<script src="../js/cookie.js"></script>//Cookie函数自己封装引入
function haxi(){
if(getCookie("isClose")){
$(".header").hide();
}else{
$(".header").show();
}

$(".close").click(function(){
$(".header").fadeOut(1000);

the setCookie ( "isclose", ". 1", "S10");
})
}
haxi ();
`` `
cookie advantages: a very high availability and scalability
1. good programming, control stored in the cookie the size of the session objects.
2. encryption and secure transmission technology, reducing the likelihood of cookie being cracked.
3. store not only sensitive data in a cookie, even if they are stolen there will be no great loss.
4. Control cookie lifetime, so that it will not always be effective. So thieves are likely to get it is an expired cookie.

The cookie disadvantages:
to limit the length and number of 1.cookie. Each domain can only have a maximum of 20 cookie, each cookie can not exceed 4KB. Otherwise it will be cut off.
2. Security issues. If the cookie was stopped out, that person can get all the information session. Encryption, then nothing happens here.
3. Some state can not be stored in the client. For example, in order to prevent duplicate submission form, we need to save a counter on the server. If the bar counter is stored in the client, it will not achieve any effect.

** ** Number of browsers allow cookie for each domain name contains:
* an increase in the Microsoft pointed InternetExplorer8 cookie limit for each domain 50, but IE7 seems to allow 50 per domain cookie.
Firefox cookie for each domain name is limited to 50.
Opera per-domain cookie limit of 30.
Safari / WebKit seemingly no cookie limit. But if a lot of cookie, will make the header size exceeds the limit processing server, it would cause an error.
Note: "Each domain cookie limit of 20" will no longer be correct! *

** As many cookie is set, the browser how to respond. **
In addition to Safari (you can set all the cookie, regardless of the number of how many), there are two methods:
  the least recently used (leastrecentlyused (LRU)) method: When Cookie limit has been reached, the oldest automatically kicks in addition to Cookie, so to date the Cookie some space. Internet Explorer and Opera use this method.

  Firefox is unique: Although Cookie always reserved the final set, but it seems to randomly decide which cookie is retained. It seems to be no plan (Recommendation: Do not exceed the limit Cookie in Firefox).


** between different browsers total cookie size is also different: **
 Firefox and Safari cookie allows up to 4097 bytes, including the name (name), value (value) and the equal sign.
 Opera cookie allows up to 4096 bytes, including: name (name), value (value) and the equal sign.
 Internet Explorer cookie allows up to 4095 bytes, including: name (name), value (value) and the equal sign.
NOTE: multi-byte character is calculated as two bytes. In all browsers, cookie any size exceeds the limit are ignored, and will never be set.

** XIII event mechanism ** (too many Baidu)

** fourteen, setTimeout mechanism (Recommended: https:? //Www.jianshu.com/p/3e482748369d from = groupmessage) **

** Fifth, encounter compatibility problems, how to deal with **
1, the inner and outer margins (initialization CSS style or the normalize)
2, the default picture at a distance (Run the display: Block / float)
3, label the lowest height setting min -height incompatible (min-height: 200px; height:! Auto Important; height: 200px; overflow: visible;)
. 4, the default interface will be less than the chrome 12px Chinese text in accordance with the forced display 12px (css attributes add -webkit- ADJUST-size-text: none;)
. 5, a number of mobile end devices do not support audio and vedio Autoplay (
document.addEventListener ( 'touchstart', function () {
document.getElementsByTagName ( 'audio') [0] .play ( );
document.getElementsByTagName ( 'Audio') [0] .pause ();
});)
. 6, IE5-IE8 does not support Opacity (
the Opacity: 0.8;
the filter: Alpha (Opacity = 80);
-ms-filter: " progid: DXImageTransform.Microsoft.Alpha (opacity = 80) ";)

7, Firefox dashed box appears click on the link (a {outline: none;} a: focus {outline: none;})

8, css3 kinds hack

 

 

 

 

 

 

 

 


Reference part interview questions or answers, if any omissions, please private letter supplement.
https://blog.csdn.net/zhang6223284/article/details/81273180
https://blog.csdn.net/weixin_34116110/article/details/88624479
https://blog.csdn.net/qq_39207948/article/details/ 81,067,482

 

Guess you like

Origin www.cnblogs.com/daizhong/p/11896312.html