In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
Editor to share with you what JS knowledge points, I believe that most people do not know much about it, so share this article for your reference, I hope you will learn a lot after reading this article, let's go to know it!
Temporary dead zone
As long as the let command exists in the block-level scope, the variables it declares are "bound" to this area and are no longer subject to external influence. This may be a little abstract, for example:
Var temp = 123 if (true) {console.log (temp); let temp;}
Results:
> ReferenceError: temp is not defined
Within the code block, the variable is not available until it is declared using let. Grammatically, it is called a "temporary dead zone". (temporal dead zone)
ES6 stipulates that temporary dead zones and let and const statements do not promote variables, mainly to reduce run-time errors and prevent the use of this variable before the variable declaration, resulting in unexpected behavior.
Call and apply methods
Both methods can change the context object of a function, but accept parameters in a different way.
Call receives comma-separated parameters.
Apply receives a list of parameters.
I'm sure you've seen code like this:
Var arr = [1,2,3]; var max = Function.prototype.apply.call (Math.max, null, arr); console.log (max); / / 3
So how do you understand this code?
1. Think of Function.prototype.apply as a whole
(Function.prototype.apply) .call (Math.max, null, arr)
2.func.call (context, args) can be converted to context.func (args)
So the code is converted to:
Math.max.apply (undefined, arr)
Basically, there is no need to explain at this point.
So have you ever tried to swap call and apply?
Var arr = [1,2,3]; var max = Function.prototype.call.apply (Math.max, null, arr); console.log (max); / /-Infinity
Why is its output-Infinity?
Because the second argument to apply must be an array, which is not here, the argument cannot be passed correctly to the call function.
According to func.apply (context, args) can be converted to context.func (args). So it is converted to Math.max.call (), and the direct call outputs-Infinity.
If you want to make the call correctly, you should write:
Var arr = [1,2,3]; var max = Function.prototype.call.apply (Math.max, arr); console.log (max); / / 3
To consolidate the above, take a look at an interview question:
Var a = Function.prototype.call.apply (function (a) {return a;}, [0mai 4jue 3]); alert (a)
What is the pop-up a value of the analysis?
/ / treat the call method as a whole (Function.prototype.call) .apply (function (a) {return a;}, [0meme 4jue 3]); / / func.apply (context, args) can be converted to context.func (... args) (function (a) {return a;}) .call (0je 4jue 3); / / so the result is obvious, the output 4Proxy object
Function: use to customize the actions in the object.
Let p = new Proxy (target, handler)
Target represents the object to which the proxy needs to be added, and handler uses to customize the operations in the object, such as custom set or get functions.
Let's look at a little chestnut:
/ / onChange is the listening operation to be performed var watch = (object, onChange) = > {const handler = {/ / if the value corresponding to the attribute is an object, a new Proxy object get (target, property, receiver) {try {return new Proxy (target [property], handler);} catch (err) {return Reflect.get (target, property, receiver) is returned }, / / define or modify object properties defineProperty (target, property, descriptor) {onChange ('define',property); return Reflect.defineProperty (target, property, descriptor);}, / / delete object properties deleteProperty (target, property) {onChange (' delete',property); return Reflect.deleteProperty (target, property);}}; return new Proxy (object, handler);} / / Test object var obj = {name: 'bjw', age: 22, child: [1,2,3]} / / object proxy var p = watch (obj1, (type, property) = > {console.log (`type: ${type}, modified attribute: ${property}`)}) P.name = 'qwe' type: define, modified attribute: name "qwe" p.child Proxy {0: 1, 1: 2, 2: 3, length: 3} p.child.push (4) Type: define, modified attribute: 3 type: define, modified attribute: length 4p.child.length = 2 type: define, modified attribute: length 2p.child Proxy {0: 1, 1: 2, length: 2}
If you follow the progress of Vue, you may already know that Vue3.0 will use Proxy to replace the original Object.defineProperty to achieve data response. The reason for replacing the original API with Proxy is that Proxy does not need to add proxies for each attribute layer by layer recursively to do this at once. The performance is better, and there are some data updates in the original implementation that cannot be monitored, but Proxy can perfectly listen for data changes in any way. I believe the advantages brought by Proxy can be felt through the above example. The only drawback may be that browser compatibility is not very good.
Reflect object
Why should there be such an object?
Using a single global object to store these methods keeps other JavaScript code clean and clean. (otherwise, it will have to be called through the prototype chain)
Some imperative operations such as delete and in are replaced by functions in order to make the code easier to maintain and avoid more reserved words.
The Reflect object has the following static methods:
Reflect.apply
Reflect.construct
Reflect.defineProperty
Reflect.deleteProperty
Reflect.enumerate / / abandoned
Reflect.get
Reflect.getOwnPropertyDescriptor
Reflect.getPrototypeOf
Reflect.has
Reflect.isExtensible
Reflect.ownKeys
Reflect.preventExtensions
Reflect.set
Reflect.setPrototypeOf
Details of the function:
Reflect.apply (target, this, arguments) / / target: objective function / / this: bound context object / / arguments: function argument list Reflect.apply (target, this, arguments) const arr = [2,3,4,5,6]; let max;// ES6max = Reflect.apply (Math.max, null, arr) / / ES5 max = Math.max.apply (null, arr); max = Function.prototype.apply.call (Math.max, null, arr) Reflect.construct (target, argumentsList [, newTarget]) / / this method provides a new method function A (name) {console.log ('Function An is invokedcalls') without using new; this.name = name;} A.prototype.getName = function () {return this.name;}; function B (age) {console.log ('Function B is invokedfunctions'); this.age = age;} B.prototype.getAge = function () {return this.age;} / / Test (the two are consistent) var tom = new A ('tom'); var tom = Reflect.construct (A, [' tom']); / / jnney inherits the instance property of An and the shared property of B / / in short, the A constructor is called, but jnney.__proto__ = = B.prototypevar jnney = Reflect.construct (A, ['jnney'], B); Reflect.defineProperty (target, propertyKey, attributes)
This method is similar to Object.definePropperty (property definition failure, which throws an error, and success returns the object), except that Reflect.defineProperty (property definition failure, returns false, success returns true) returns a Boolean value.
Let obj = {}; let obj1 = Object.defineProperty (obj, 'name', {enumerable: true, value:' bjw'}); / / false is returned here because the attribute name defined above is immutable, / / and then we modify the name property here, so the failed modification returns a value of falselet result1 = Reflect.defineProperty (obj, 'name', {configurable: true, enumerable: true, value:' happy'}) Console.log (result1); / / falseReflect.deleteProperty (target, propertyKey) let obj = {name: 'dreamapple', age: 22}; let R1 = Reflect.deleteProperty (obj,' name'); console.log (R1); / / truelet R2 = Reflect.deleteProperty (obj, 'name'); console.log (R2); / / truelet R3 = Reflect.deleteProperty (Object.freeze (obj),' age'); console.log (R3); / / falseReflect.get (target, propertyKey [, receiver])
Reflect.set (target, propertyKey, value [, receiver])
This method is used to read / set the properties of an object, target is the target object, propertyKey is the property we want to read, receiver is optional, if there is a getter value in the getter function of propertyKey, then receiver is the context represented by this object.
Reflect.getOwnPropertyDescriptor (target, propertyKey)
This method is similar to the Object.getOwnPropertyDescriptor method, where target is the target object and propertyKey is the property of the object, which is returned if there is a property descriptor for this property, or undefined if it does not exist. (if the first parameter is not an object, Object.getOwnPropertyDescriptor will cast the parameter to an object, and the method Reflect.getOwnPropertyDescriptor will throw an error.)
Var obj = {age: 22} Reflect.getOwnPropertyDescriptor (obj, 'age') {value: 22, writable: true, enumerable: true, configurable: true} Reflect.getPrototypeOf (target)
Reflect.setPrototypeOf (target, prototype)
This method is the same as the Object.getPrototypeOf method, which returns the prototype of an object, that is, the value of the internal [[Prototype]] property.
The function of the Reflect.setPrototypeOf method is similar to that of the Object.setPrototypeOf method. Set the prototype of an object. If the setting is successful, the object will return a true;. If the setting fails, the object will return a false.
Reflect.has (target, propertyKey)
This method is equivalent to ES5's in operator, which checks whether an object contains a specific property; let's continue to practice this method:
Function A (name) {this.name = name | | 'dreamapple';} A.prototype.getName = function () {return this.name;}; var a = new A (); console.log (' name' in a); / / trueconsole.log ('getName' in a); / / truelet R1 = Reflect.has (a,' name'); let R2 = Reflect.has (a, 'getName'); console.log (R1, R2); / / true trueReflect.isExtensible (target)
This function checks whether an object is extensible, that is, whether new properties can be added. (requires that target must be an object, otherwise an error will be thrown)
Let obj = {}; let R1 = Reflect.isExtensible (obj); console.log (R1); / / true// seals this object Object.seal (obj); let R2 = Reflect.isExtensible (obj); console.log (R2); / / false modularization
Using modularity can bring us the following benefits:
Resolve naming conflicts
Provide reusability
Improve code maintainability
Execute the function immediately
In the early days, the immediate execution function was used to realize modularization, and the problem of naming conflict and polluting the global scope was solved through the function scope.
AMD and CMD
These two implementations are rare, and the specific ways to use them are as follows:
/ / AMDdefine (['. / averse,'. / b'], function (a, b) {/ / the module can be loaded using a.do (); b.do ();}); / / CMDdefine (function (require, exports, module) {/ / load module var a = require ('. / a');}); CommonJS
CommonJS was first used by Node and can now be seen in Webpack.
/ / a.jsmodule.exports = {a: 1} / / or exports.a = 1 / var module = require ('. / a') can be introduced in b.js; module.a / / log 1
Analysis of difficulties:
/ / module basically implements var module = {id: 'xxx', exports: {}} var exports = module.exports;//, so the variable ES Module cannot be exported by reassigning exports.
ES Module is a native implementation modularization scheme.
/ / Import module import xxx form'. / a.jsaccountingimport {xxx} from'. / b.jsimport / export module export function a () {} / / default export export default {}; export default function () {} ES Module and CommonJS difference
CommonJS supports dynamic import, that is, require (${path} / xx.js), but ES Module does not
CommonJS is a synchronous import, because for the server side, the files are local, and the synchronous import has little impact even if the main thread is stuck. While ES Module is imported asynchronously, because for browsers, you need to download files, and synchronous import will have a great impact on rendering.
CommonJS is a copy of the value when it is exported, and even if the export value changes, the imported value will not change. If you want to update the value, you must import it again. However, ES Module uses real-time binding, and the values of import and export all point to the same memory address, so the import value will change with the export value.
ES Module will be compiled into require/exports to execute.
Handwritten simple version of Promiseconst PENDING = 'pending';const RESOLVED =' resolved';const REJECTED = 'rejected';function MyPromise (fn) {const _ this = this; _ this.state = PENDING; _ this.value = null; _ this.resolvedCallbacks = []; _ this.rejectedCallbacks = []; / / resolve function function resolve (value) {if (_ this.state = = PENDING) {_ this.state = RESOLVED; _ this.value = value _ this.resolvedCallbacks.map (cb = > cb (_ this.value));}} / / rejected function function reject (value) {if (_ this.state = PENDING) {_ this.state = REJECTED; _ this.value = value; _ this.rejectedCallbacks.map (cb = > cb (_ this.value)) }} / / when creating an object, execute the incoming executor function / / and pass the resolve and reject functions try {fn (resolve, reject);} catch (e) {reject (e);} / add the then function MyPromise.prototype.then = function (onFulfilled, onRejected) {const _ this = this; onFulfilled = typeof onFulfilled = = 'function'? OnFulfilled: v = > v; onRejected = typeof onRejected = = 'function'? OnRejected: r = > {throw r;} if (_ this.state = PENDING) {_ this.resolvedCallbacks.push (onFulfilled); _ this.rejectedCallbacks.push (onRejected);} if (_ this.state = RESOLVED) {onFulfilled (_ this.value);} if (_ this.state = REJECTED) {onRejected (_ this.value);} return _ this;} / / Test new MyPromise (function (resolve, reject) {setTimeout () = > {resolve ('hello');}, 2000) }) .then (v = > {console.log (v);}) .then (v = > {console.log (v + "1");}) these are all the contents of the article "what are the knowledge points of JS". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.