JavaScript
1 Built-in Types
JS
Is divided into seven built-in types, which are divided into two main types: primitive types and reference types (object (Object
)).- There are six basic types:
null
,undefined
,boolean
,number
,string
,symbol
。 - Among them
JS
The number type is floating point, not integer. And floating point type is based on IEEE 754 standard implementation, in use will encounter some bugs,NaN
Also belong tonumber
Type, andNaN
Not equal to itself. - For primitive types, the variable is just a literal and will only be converted to the corresponding type if necessary.
let a = 111; // This is just a literal, not a number type
a.toString(); // It is converted to object type only when used
Copy the code
Object is a reference type, which may encounter the problem of shallow copy and deep copy.
let a = { name: 'fangyuan' };
let b = a;
b.name = 'yuanfang';
console.log(a.name); // yuanfang
Copy the code
2 Null and undefined
Null is an object representing “none” and is zero when converted to a value; Undefined is a primitive value for “none”, which is NaN when converted to a value.
When the declared variable has not been initialized, the default value of the variable is undefined. Null is used to indicate that an object does not yet exist, and is often used to indicate that a function attempts to return an object that does not exist.
Undefined means “missing value”, that is, there should be a value here, but it is not defined yet. Typical usage:
- (1) If a variable is declared but not assigned, it is undefined.
- (2) When the function is called, the argument that should be provided is not provided, which is equal to undefined.
- (3) The object has no assigned attribute. The value of this attribute is undefined.
- (4) If the function does not return a value, undefined is returned by default.
Null means “no object”, meaning there should be no value. Typical usage:
- (1) as the parameter of the function, indicating that the parameter of the function is not an object.
- (2) as the end of the object prototype chain.
What exactly does the new operator do
- 1. Create an empty object and
this
The variable refers to the object and inherits the prototype of the function. - Properties and methods are added to
this
Object referenced. - 3. The newly created object is created by
this
And is returned implicitly at the endthis
.
4. Similarities and differences between call, apply and bind
Bind, apply, and call can all be used to change the direction of this
Apply and call are both methods of a Function object. Each Function can be called and the first argument of each Function is the execution context you specify. The Apply method receives an array of arguments, while the Call method receives lists of arguments. Bind receives a list of arguments, but must call bind(…) once. (a)
var a = {
name: 'fangyuan'.fn: function(a, b) {
console.log(a + b); }}var b = a.fn;
b.apply(a, [1.2]); / / 3
b.call(a, 4.5.6); / / 15
Copy the code
We often use an array verification (provided the toString() method has not been overridden) :
function isArray(obj) {
return Object.prototype.toString.call(obj) === '[object Array]';
}
Copy the code
Bind/call/apply
var a = {
name: 'fangyuan';
fn: function(a, b) {
console.log(a + b); }}var b = a.fn;
b.bind(a, 1.2) ();/ / 3
Copy the code
We see that the bind() method needs to be called once more; The bind() method creates a new function that we must call manually.
Similarities and differences between bind,aplly, and Call
- All three can be changed
this
The point to - The first parameter of all three
this
The object to point to, that is, to the specified context, which is the object from which the function is called. - All three can pass in, but
apply
Is an array, andcall
和bind
Multiple arguments are passed in order. - Bind returns the corresponding function for later call;
apply
、call
Execute immediately.
5 Cross-domain problem solving
- Cross domains via JSONP
- Cross-domain Resource Sharing (CORS)
- Nodejs middleware proxies cross domains
- Nginx reverse proxy red set proxy_cookie_domain
1. Cross domains through JSONP
Usually, in order to reduce the load of the Web server, we separate static resources such as JS, CSS and IMG to another server with an independent domain name, and then load static resources from different domain names through corresponding tags in the HTML page, which is allowed by the browser. Based on this principle, we can dynamically create script tags. Request a reference url to achieve cross-domain communication.
<script>
var script = document.createElement('script); script.type = 'text/javascript'; // Pass the name of the callback function to the back end, so that the back end can execute the callback function defined in the front end script.src = 'http://www.xxx.com:8080/login?user=admin&callback=jsonCallback';
document.head.appendChild(script);
// The callback executes the function
function jsonCallback(res) {
alert(JSON.stringify(res));
}
</script>
Copy the code
2. Cross-domain Resource Sharing (CORS)
CORS is a W3C standard, fully known as “cross-origin Resource Sharing” (CROSS-domain resource Sharing). As the name suggests, this is standard practice for dealing with cross-domain problems. CORS has two types of requests, simple and non-simple.
A simple request
- The request method is
HEAD
,GET
,POST
One of three ways - The HTTP request header does not contain more than the following fields:
- Accept
- Accept-Language
- Content-Language
- Last-Event-ID
- Content-type: Only application/ X-www-form-urlencoded, multipart/form-data, text/plain
Complex requests If the front end is to have cookies, the front end also needs to be set separately
var xhr = new XMLHttpRequest();
// Set whether cookies are included in the front end
xhr.withCredentials = true; .Copy the code
3.Nodejs middleware proxy is cross-domain
Using a proxy server to forward data, or setting the cookieDomainRewrite parameter to modify the domain name in the cookie in the response header to write cookies under the current domain name
Cross-domain implementation under vUE framework
Cross domain using node + Webpack + webpack-dev-server agent interface. In the development environment, since the Vue rendering service and the interface proxy service are the same as Webpack-dev-server, there is no need to set headers cross-domain information between the page and proxy interface. You can do nothing in the background.
module.exports = {
entry: {},
module: {},...devServer: {
historyApiFallback: true.proxy: [{
context: '/login'.target: 'http://xxx.com:8080'.// Proxy cross-domain target interface
changeOrigin: true.secure: false.// Used when the agent reports an error with some HTTPS serviceCookieDomainRewrite:'xxx.com' // The value can be false, indicating no change}].noInfo: true}}Copy the code
4. Set in the Nginx reverse proxy
This is similar to using Node middleware across domains. Neither the front end nor the back end need to write additional agents to handle it, just configure Nginx
server {
listen: 80;
server_name aa.com;
location ^~ /api {
proxy_pass http://xxx.com;}}Copy the code
The difference between defer and async in the 6 Script tag
<script src="script.js"></script>
Copy the code
Without defer or Async, the browser loads and executes the specified script immediately, “immediately” before rendering the document element under the script tag, meaning that it is loaded and executed as soon as it is read without waiting for subsequent loaded document elements.
<script async scr="script.js"></script>
Copy the code
There is async, the process of loading and rendering subsequent document elements will be performed in parallel with the loading and execution of script.js (asynchronous).
<script defer src="script.js"></script>
Copy the code
With defer, the loading of subsequent document elements will take place in parallel (asynchronously) with the loading of script.js, but the execution of script.js will be completed after all elements have been parsed and before the DOMContentLoaded event is fired.
The blue line represents network reads, and the red line represents execution time, both of which are for scripting; The green line represents HTML parsing.
7 Data type conversion
Implicit conversion occurs when using operators or contrast characters in JS. The rules are as follows:
Transformation rules
-
,*
,/
,%
: All conversion into numerical calculation+
:- Number + string = string, from left to right
- Number + object, which calls the object first
valueOf -> toString
- Digital +
boolean/null
– > digital - Digital +
undefined -> NaN
[1].toString() === '1'
{}.toString() === '[object object]'
NaN ! == NaN
,+undefined
forNaN
There are only three types of conversion in JS:
- Converts to a Boolean value
- Convert to numbers
- Convert to string
The original value | Transformation goal | The results of |
---|---|---|
number | Boolean value | All except 0, -0, and NaN are true |
string | Boolean value | True for all but empty strings |
Undefined, null, | Boolean value | false |
Reference types | Boolean value | true |
number | Boolean value | 5 = > ‘5’ |
Boolean, function, Symbol | string | ‘true’ |
An array of | string | [1, 2] => ‘1, 2’ |
object | string | ‘[Object Object]’ |
string | digital | ‘1’ => 1, ‘a’ => NaN |
An array of | digital | The empty array is 0, there is one element and the number is converted to a number, otherwise NaN |
null | digital | 0 |
Except for the reference type of the array | digital | NaN |
Symbol | digital | Throw the wrong |
8 JavaScript – for… In, for… Differences between of and forEach
for… in for… In iterates over all enumerable properties (iterating object properties) in an object, including inherited enumerable properties. It can iterate over arrays, strings, or plain objects, but not over maps or sets.
for (let prop in ['a'.'b'.'c'])
console.log(prop); // Output the index of the array: 0, 1, 2
for (let prop in 'str')
console.log(prop); // Index of the output string: 0, 1, 2
for (let prop in {a: 1.b: 2.c: 2})
console.log(prop); // Outputs the attributes of the object: a, b, c
for (let prop in new Set(['a'.'b'.'c']))
console.log(prop); // There are no enumerable attributes and the output is empty
Copy the code
for… of for… Of iterates over objects that can be iterated over, but it iterates over the value of the object, not its properties. It can iterate over arrays, strings, maps, or sets, but not over normal objects.
for (let val of ['a'.'b'.'c'])
console.log(val); // Outputs the array values: a, b, c
for (let val of 'str')
console.log(val); // Outputs the characters in the string: s, t, r
for (let val of {a: 1.b: 2.c: 3})
console.log(val); // Intermediate value is not iterable
for (let val of new Set(['a'.'b'.'c']))
console.log(val); // 输出 Set 值: a, b, c
Copy the code
ForEach () forEach() is a method on the Array prototype that allows you to iterate over each element in the Array. ForEach () can only iterate over an array, but it can access the value and index of each element as it iterates.
['a'.'b'.'c'].forEach(val= > console.log(val)); // Outputs the array values: a, b, c
['a'.'b'.'c'].forEach((val, i) = > console.log(i)); // Output the index of the array: 0, 1, 2
Copy the code
9 How do I disable web page copy and paste
You’re probably no stranger to banning copy and paste from web pages. Some pages are directly forbidden to copy and paste; Some web pages, it is required to log in to copy and paste; And some sites, copy and paste with the site’s source identification information.
- How to prevent web page copy and paste
const html = document.querySelector('html); html.oncopy = () => { alert('You copy it'); return false; }; html.onpaste = () => false;Copy the code
- Do something else while copying, such as jump to the login page
const html = document.querySelector('html');
html.oncopy = (e) = > {
console.log(e);
// For example, point to Baidu or the landing page
window.location.href = 'http://www.baidu.com';
};
html.onpaste = (e) = > {
console.log(e);
}
Copy the code
- How to set/get clipboard content using JS
// Set the clipboard contents
document.addEventListener('copy'.() = > {
constclipboardData = event.clipboardData || event.originalEvent ? .clipboardData; clipboardData? .setData('text/plain'.'Whatever you copy, it's me! ');
event.preventDefault();
});
// Get the clipboard contents
document.addEventListener('paste'.() = > {
constclipboardData = event.clipboardData || event.originalEvent? .clipboardData;consttext = clipboardData? .getData('text');
console.log(text);
event.preventDefault();
})
Copy the code