Front sunflower treasure book, escort for you gold three silver four

Source: making stars ✨ | o | give a ❤ ️ attention, ❤ ️ thumb up, ❤ ️ encourages the author

Grass: the harder you work, the luckier you will be! With the current low level of effort of most people, it is impossible to compete for talent.

Share the front end interview secret, hope to help more small partners. Add me 😚 can exchange problems (not big guy, learn from each other, create a good learning environment). Which of the following do you not understand?

  • First pay attention to the public number: wechat search: programmer Doraemon
  • QQ group 1:7 11613774 (full)
  • QQ group 2:634382181
  • Wechat account: Xiaoda0423 (Note sent: Have followed Nezha)

One side

One side of the question is not difficult, but to get a high evaluation of the interviewer, or need a certain ability of expression and understanding of the nature of the comparison of technology, if you can do some appropriate expansion in the answer to the question, naturally will let the interviewer have a different evaluation of you.

Steps to answer the question: first answer the essence of the question, then answer the details, and finally do some usual programming extensions. The interviewer will think that you have really put some effort into this technique.

Second interview

The questions are straightforward, and the answers are either you know or you don’t know. These questions are partly basic and partly based on your expertise.

It’s normal to have some questions you don’t answer in an interview, but being able to surprise the interviewer is an important plus.

On three sides

I will ask more about the project, and I must go deep into the project I have done, including the principle of the technology used and why I want to use these technologies.

How did you achieve an important point in the project (which required in-depth technical principles), what were the biggest difficulties encountered (what were the difficulties), and how did you solve them? If you need to extend a certain function, how to reduce the coupling degree of the system, if you optimize for a certain function, how to design and optimize.

All around

Basically see your potential (have the value that raises namely), but still can be seen from your study at ordinary times come.

Five surface

Integrity is Paramount, so don’t include any false information in your resume. It can do more harm than good to try to get an interview through false information. Have a clear career plan, ability to express oneself, ability to get along with colleagues and attitude to work.

arguments[]Function parameter array

The arguments[] array is defined only in the function body.

In the function body, arguments refers to the arguments object of the function. This object has numeric attributes and can be used as an array, containing all the parameters passed into the function. The arguments identifier is essentially a local variable that is automatically declared and initialized in each function.

Arguments refers to arguments objects only in the function body, undefined in global code.

Arguments to the function Arguments and other properties.

The Arguments object is defined only in the function body. Technically, the Arguments object is not an array, but it does have numeric and Length properties.

The numeric type can be thought of as an array element, and the Length attribute represents the number of array elements that are the parameter values passed to the method. Element 0 is the first argument, element 1 is the second argument, and so on.

All values passed as Arguments become array elements of the Arguments object, even if parameter names are not specified in the function declaration.

Callee and Length attributes.

  1. The callee attribute refers to the function currently being executed
  2. The number of Arguments passed to the function by the Length property, and the number of array elements in the Arguments object

Argumentsobject

Arguments is an array-like object corresponding to the arguments passed to the function.

Example:

function func1(a, b, c) {
  console.log(arguments[0]);
  // expected output: 1

  console.log(arguments[1]);
  // expected output: 2

  console.log(arguments[2]);
  // expected output: 3
}

func1(1, 2, 3);
Copy the code

Can be converted to a real Array:

var args = Array.prototype.slice.call(arguments);
var args = [].slice.call(arguments);

// ES2015
const args = Array.from(arguments);
const args = [...arguments];
Copy the code

Arguments objects are used for:

  • It is used to determine how many arguments are passed into the function, and can also be used to refer to unnamed arguments
  • In addition to array elements and length attributes, anonymous functions themselves can be referred to through the Callee attribute.

Arguments.callee The function that is currently executing

Arguments.callee, which refers to the currently executing function, by which you can reference the anonymous function itself. This attribute is defined only in the function body.

Example:

Var fn = function(x) {if(x<2) return 1; else return x * arguments.callee(x-1) } var y = fn(5); / / 120Copy the code

Arguments.length Specifies the number of Arguments passed to the function

Arguments. length, the length property of the arguments object indicates the number of arguments to give to the current function. This attribute can only be defined in the function body.

This property represents the actual number of arguments passed, not the declared number.

Example:

Alert (" argument length: "+arguments.length); Alert (" parameter length: "+arguments.callee.length); Function check(args) {var actual = args. Length; Var Expected = args.callee.length; If (actual! = expected) {throw new Error(" + expected + "; "+ actual); } } function fn(x,y,z) { check(arguments); Return x+y+z; }Copy the code

Object.keys()

The object.keys () method returns an array of a given Object’s own enumerable properties in the same order as the property names would be returned if the Object were iterated through normally.

grammar

Object.keys(obj)
Copy the code

parameter

obj

To return an object that enumerates its own properties.

The return value

An array of strings representing all the enumerable properties of a given object.

Example:

// simple array var arr = ['a', 'b', 'c']; console.log(Object.keys(arr)); // console: ['0', '1', '2'] // array like object var obj = { 0: 'a', 1: 'b', 2: 'c' }; console.log(Object.keys(obj)); // console: ['0', '1', '2'] // array like object with random key ordering var anObj = { 100: 'a', 2: 'b', 7: 'c' }; console.log(Object.keys(anObj)); // console: ['2', '7', '100'] // getFoo is a property which isn't enumerable var myObj = Object.create({}, { getFoo: { value: function () { return this.foo; }}}); myObj.foo = 1; console.log(Object.keys(myObj)); // console: ['foo']Copy the code

Object.getOwnPropertyNames()

Object. GetOwnPropertyNames () method returns a specified by the Object of all its attributes of the attribute name (including not enumerated attribute but does not include Symbol value as the name of the attribute) consisting of an array.

Syntax Object. GetOwnPropertyNames (obj)

parameter

obj

The names of an object’s own enumerable and non-enumerable properties are returned.

The return value

An array of strings corresponding to its properties found on the given object.

Example:

var arr = ["a", "b", "c"]; console.log(Object.getOwnPropertyNames(arr).sort()); / / / "0", "1", "2", "length"] / var/class array object obj = {0: "a", 1: "b", 2: "c"}; console.log(Object.getOwnPropertyNames(obj).sort()); / / / "0", "1", "2"] / / using Array forEach output attribute name and attribute value Object. GetOwnPropertyNames (obj). ForEach (function (val, independence idx, array) { console.log(val + " -> " + obj[val]); }); Var my_obj = object.create ({}, {getFoo: {value: function() { return this.foo; }, enumerable: false } }); my_obj.foo = 1; console.log(Object.getOwnPropertyNames(my_obj).sort()); // ["foo", "getFoo"]Copy the code

Object.create()

The object.create () method creates a new Object, using an existing Object to provide the __proto__ of the newly created Object.

const person = { isHuman: false, printIntroduction: function() { console.log(`My name is ${this.name}. Am I human? ${this.isHuman}`); }}; const me = Object.create(person); me.name = 'Matthew'; // "name" is a property set on "me", but not on "person" me.isHuman = true; // inherited properties can be overwritten me.printIntroduction(); // expected output: "My name is Matthew. Am I human? true"Copy the code

Syntax Object.create(proto, [propertiesObject])

parameter

proto

The prototype object of the newly created object.

propertiesObject

Optional. You need to pass in an object whose own enumerable properties (that is, properties defined by itself, not enumerated properties in its stereotype chain) add the specified property values and corresponding property descriptors to the newly created object.

The return value

A new object with the specified prototype object and properties.

exception

If the propertiesObject argument is null or a non-original wrapped object, a TypeError exception is thrown.

withObject.createImplement class inheritance

// Shape - superclass function Shape() {this.x = 0; this.y = 0; Function (x, y) {this.x += x; // function(x, y) {this.x += x; this.y += y; console.info('Shape moved.'); }; // Rectangle - subclass (subclass) function Rectangle() {shape.call (this); Rectangle. Prototype = object.create (Shape. Prototype); // Rectangle. Rectangle.prototype.constructor = Rectangle; var rect = new Rectangle(); console.log('Is rect an instance of Rectangle? ', rect instanceof Rectangle); // true console.log('Is rect an instance of Shape? ', rect instanceof Shape); // true rect.move(1, 1); // Outputs, 'Shape moved.'Copy the code

If you want to inherit multiple objects, you can use mixin.

function MyClass() { SuperClass.call(this); OtherSuperClass.call(this); Prototype = object.create (superclass.prototype); / / mixed other Object. The assign (MyClass. Prototype, OtherSuperClass. Prototype); / / to specify the constructor MyClass. Prototype. Constructor = MyClass; MyClass.prototype.myMethod = function() { // do a thing };Copy the code

Object.assign copies functions from the OtherSuperClass prototype to the MyClass prototype, making all instances of MyClass available to OtherSuperClass methods.

useObject. The create propertyObjectparameter

var o; // Create an empty Object with the prototype null o = object.create (null); o = {}; // An empty Object created literally is equivalent to: o = object.create (object.prototype); Foo: {writable:true, different :true, value: 64x: disables any additional information that works without any additional control. Bar: {64x: false, get: function() {return 10}, set: disables any additional information, disables any additional information, and disables any additional information. function(value) { console.log("Setting `o.bar` to", value); }}}); function Constructor(){} o = new Constructor(); O = object.create (Constructor. Prototype); O = object.create ({}, {p: {value:); // If there is some initialization code in the Constructor function, object.create cannot execute that code // Create an Object based on another empty Object with an attribute p o = object.create ({}, {p: {value:) 42}}) // The omitted attribute defaults to false, so p is not writable, enumerable, or configurable: O.p = 24 o.p //42 o.q = 12 for (var prop in o) {console.log(prop)} //"q" delete o.p //false // create a writable, enumerable, configurable property = Object.create({}, { p: { value: 42, writable: true, enumerable: true, configurable: true } });Copy the code

Vue preparation

  • Learn to understand flow, Vuejs source directory design, Vuejs source code construction, from the entrance (understand Vue preparation).
  • FlowisfacebookJavaScriptStatic type checking tool.
  • VueThe source code is utilizedflowStatic type checking was done.

How flow works:

Generally, there are two types of type checking: type inference; Second: type annotations.

What is type inference?

Infer the type of a variable from its context.

What are type annotations?

The desired type is annotated beforehand, and flow determines based on these annotations.

In the home directory of Vuejs there is the. Flowconfig file, which is the flow configuration file, and the [libs] section which describes the directory containing the definition of the specified library.

Flow folder directory:

  1. compiler.jsCompile related
  2. component.jsComponent data structure
  3. global-api.jsThe global structure of the API
  4. modules.jsThird-party Library Definitions
  5. options.jsOption related
  6. ssr.jsServer side rendering is relevant
  7. vnode.jsVirtual Node Related

Vue. Js source directory SRC:

  1. compilerCompile related
  2. coreThe core code
  3. platformsDifferent platform support
  4. serverServer side rendering
  5. sfc.vueFile parsing
  6. sharedTo share code

The Vuejs source code is built based on Rollup.

Vue initialization process

Recommended: Vue initialization process

The flow chart of the init

The essence of Vue: It’s basically a Class implemented with Function, with a set of methods and properties extended through its prototype.

To gain a deeper understanding of the data rendering process, starting with new Vue(), we create a Vue is object, Start init — >$mount() — >compile(render is not required) — >render — > create VNode — >patch process — > generate real DOM

null

If you want T of any type to be null or undefined, you just say, okay? The format of T.

Var foo: string = null // Can be a string or nullCopy the code

Why and what is the purpose of a list component in a Vue project

Key is the unique ID given to each Vnode. You can rely on the key to get the corresponding VNode in oldVnode more accurately and faster.

['1','2','3'].map(parseInt)

The answer is [1,NaN,NaN], why not [1,2,3]?

The map function’s first argument, callback, can take three arguments, the first parameter representing the element being processed and the second parameter representing the index of that element.

arr.map(callback: (value:T, index: number, array: T[]) => U, thisArg? :any);Copy the code
  • ParseInt is used to parse a string, making it an integer of the specified cardinality. Accepts two arguments, the first representing the value being processed (string) and the second representing the cardinality at parsing time.
parseInt(string, radix);
Copy the code

ParseINT (‘1’, 0) indicates that when radix is 0 and the string parameter does not start with “0x” and “0”, the radix is treated as base 10 and returned as 1.

ParseInt (‘2’,1), base 1 (1), represents a number that is less than 2, so it cannot parse, return NaN.

What is anti-shake and throttling

Anti – shake, literally placing the hand shake again triggered.

onReachBottom() {
    this.timer && clearTimeout(this.timer)
    this.timer = setTimeout(this.getMoreList, 300)
},
Copy the code

The function is executed only once n seconds after the high-frequency event is triggered. If the high-frequency event is triggered again within n seconds, the time needs to be recalculated.

/ / the Denver nuggets: Function debounce(fn) {let timeout = null return function() {return function() { ClearTimeout = setTimeout(() => {// Create a new setTimeout, This ensures that the fn function fn.apply(this, arguments) will not be executed if more characters are entered within the interval after the string; }} function sayHi() {console.log(' console.log ')} var inp = document.getelementById ('inp'); inp.addEventListener('input',debounce(sayHi)); / / image stabilizationCopy the code

Throttling, literally saving traffic, is triggered by a high frequency event, but is executed only once in n seconds, so throttling dilutes the execution frequency of the function.

// Function throttle(fn) {let canRun = true; Return function() {if(! CanRun) return // Check whether the flag is true at the beginning of the function, SetTimeout (() => {fn.apply(this,argument); // Set the setTimeout flag to true to indicate that the next loop can be executed. CanRun = true},500)}} function sayHi(e) {console.log(e.target.innerWidth, e.target.innerHeight) } window.addEventListener('resize', throttle(sayHi));Copy the code

Set, Map, WeakSet, WeakMap

Set, an object that allows you to store a unique value of any type, either a primitive value or an object reference

Weakset, members are all objects, members are weak references, can be recycled by garbage collection mechanism, can be used to save DOM nodes, not easy to cause memory leakage.

A Map, essentially, is a collection of key-value pairs, like a collection, that can be traversed in a variety of ways, and can be converted to a variety of data formats.

WeakMap only accepts the object as the key name (except null), and does not accept other types of values as the key name. The key name is a weak reference, and the key value can be arbitrary, and the object pointed to by the key name can be garbage collected. At this time, the key name is invalid and cannot be traversed

Depth-first and breadth-first traversal

Depth-first traversal

It refers to starting from a vertex, accessing that vertex first, finding the first unvisited neighbor that just accessed that vertex, and then using that neighbor as its vertex and continuing to find its next vertex to access. Repeat this step until all nodes are accessed.

Breadth-first traversal

It starts with a vertex, accesses that vertex first, finds all the unvisited neighbors that just visited that node, and then accesses all of the first neighbors of those nodes, and repeats this method until all nodes are accessed.

Function deepTraveral(node) {let nodes = [] if(node! = null) { nodes.push[node] let childrens = node.children for(let i=0; i<childrens.length; i++) deepTraversal(childrens[i]) } return nodes }Copy the code
Function deepTraversal(node) {let nodes = [] if(node! = null) {let stack = [] // To store the node to be accessed in the future. Push (item) let childrens = item.children for(let I = childrens. Length -1; i>=0; I --) stack.push(childrens[I]) // Add children of nodes to stack for future access}} return nodes}Copy the code
Function wideTraversal(node) {let nodes = [], I = 0 if(node! = null) { nodes.push(node) wideTraversal(node.nextElementSibling) node = nodes[i++] wideTraversal(node.firstElementChild) } return nodes }Copy the code
Function wideTraversal(node) {let nodes = [], I =0 while(node! = null) { nodes.push(node) node = nodes[i++]; let childrens = node.children for(let i=0; i<childrens.length; i++) { nodes.push(childrens[i]) } } return nodes }Copy the code

Implement a copy function?

Object.prototype.toString()

The toString() method returns a string representing the object.

function Dog(name) { this.name = name; } const dog1 = new Dog(' Nezha '); Dog.prototype.toString = function dogToString() { return `${this.name}`; }; console.log(dog1.toString()); Expected Output: "Ne Zha"Copy the code

grammar

Obj.tostring () // Returns the value // a string representing the object.Copy the code

Each object has a toString() method, which is called automatically when the object is represented as a text value, or when an object is referenced as an expected string. By default, the toString() method is inherited by each Object. If this method is not overridden in a custom object, toString() returns “[Object type]”, where type is the type of the object.

var o = new Object();
o.toString(); // returns [object Object]
Copy the code

Detect object types using toString()

You can get the type of each object by toString(). To every Object through the Object. The prototype. The toString () to test, need to Function. The prototype. The call () or the Function. The prototype, the apply () in the form of a call, Pass the object to be checked as the first argument, called thisArg.

Example:

var toString = Object.prototype.toString; toString.call(new Date); // [object Date] toString.call(new String); // [object String] toString.call(Math); // [object Math] //Since JavaScript 1.8.5 tostring. call(undefined); // [object Undefined] toString.call(null); // [object Null]Copy the code

Function.prototype.call()

The call() method calls a function with a specified this value and one or more arguments given separately.

The call() method takes a list of arguments

Example:

Function Product(name, price) {this.name = name; this.price = price; } function Food(name, price) { Product.call(this, name, price); this.category = 'food'; } console.log(new Food('cheese', 5).name); // expected output: "cheese"Copy the code

grammar

function.call(thisArg, arg1, arg2, ...)
Copy the code

thisArg

Optional. The this value used when function is run. Note that this may not be the actual value seen by the method: if the function is in non-strict mode, specifying null or undefined is automatically replaced with pointing to a global object, and the original value is wrapped.

arg1, arg2, ...

Specifies the argument list.

The return value

Call the return value of the function with the this value and arguments provided by the caller. If the method returns no value, undefined is returned.

describe

Call () allows different objects to assign and call functions/methods belonging to one object.

Call () provides the new this value for the currently called function/method. You can use Call to implement inheritance: write a method and then have a new object inherit it (instead of writing the method again in the new object).

Call the parent constructor using the call method

Example:

Function Product(name, price) {this.name = name; this.price = price; } function Food(name, price) { Product.call(this, name, price); this.category = 'food'; } function Toy(name, price) { Product.call(this, name, price); this.category = 'toy'; } var cheese = new Food('feta', 5); var fun = new Toy('robot', 40);Copy the code

Function.prototype.apply()

The apply() method calls a function with a given this value and arguments in the form of an array (or array-like object).

grammar

// thisArg, [argsArray]Copy the code

parameter

thisArg

Will be selected. The this value used when the func function is run. Note that this may not be the actual value seen by the method: if the function is in non-strict mode, specifying null or undefined is automatically replaced with pointing to a global object, and the original value is wrapped.

argsArray

Optional. An array or array-like object whose array elements are passed as individual arguments to the func function. If the value of this parameter is null or undefined, no arguments need to be passed in. Array-like objects can be used starting with ECMAScript 5.

The return value

The result of calling a function with the specified this value and argument.

describe

When calling an existing function, you can specify a this object for it. This refers to the current object, the object on which the function is being called. With Apply, you can write the method once and then inherit it from another object instead of repeating the method in a new object.

Use Apply to add the array items to another array

Var array = ['a', 'b']; var elements = [0, 1, 2]; array.push.apply(array, elements); console.info(array); // ["a", "b", 0, 1, 2]Copy the code

Function.prototype.bind()

The bind() method creates a new function, and when bind() is called, this of the new function is specified as the first argument to bind(), and the remaining arguments will be used as arguments to the new function.

// Const module = {x: 42, getX: function() {return this.x; }}; const unboundGetX = module.getX; console.log(unboundGetX()); // The function gets invoked at the global scope // expected output: undefined const boundGetX = unboundGetX.bind(module); console.log(boundGetX()); // expected output: 42Copy the code

grammar

/ / the Denver nuggets: Lord which zha function. The bind (thisArg [, arg1, arg2 [[,...]]])Copy the code

The return value

Returns a copy of the original function with the specified this value and initial arguments.

Creating a binding function

// Nezha: this.x = 9; Var module = {x: 81, getX: function() {return this.x; }}; module.getX(); // 81 var retrieveX = module.getX; retrieveX(); // Return 9 - because the function is called in global scope // Create a new function, // A novice may confuse the global variable x with the module property x var boundGetX = retrievex.bind (module); boundGetX(); / / 81Copy the code

By default, when window.setTimeout() is used, the this keyword points to the window (or global) object. When you need this to refer to an instance of the class in a method of the class, you may need to explicitly bind this to the callback function without losing a reference to the instance.

Convert an array-like object into a real array

// var slice = array.prototype. Slice; / /... slice.apply(arguments);Copy the code

Array.prototype.slice()

The slice() method returns a new array object that is a shallow copy (including begin, but not end) of the array determined by begin and end. The original array will not be changed.

// Const animals = ['ant', 'bison', 'Camel ', 'duck', 'elephant']; console.log(animals.slice(2)); // expected output: Array ["camel", "duck", "elephant"] console.log(animals.slice(2, 4)); // expected output: Array ["camel", "duck"] console.log(animals.slice(1, 5)); // expected output: Array ["bison", "camel", "duck", "elephant"]Copy the code

grammar

Slice ([begin[, end]])Copy the code

The return value

A new array containing the extracted elements.

describe

Slice does not modify the original array, but only returns a new array that copies elements in the original array. Elements of the original array are copied according to the following rules:

If the element is an object reference (not an actual object), Slice copies the object reference into the new array. Both object references refer to the same object. If the referenced object changes, the element in the new and original array changes as well.

For strings, numbers, and Booleans (not String, Number, or Boolean objects), Slice copies these values into the new array. Modifying these strings or numbers or booleans in another array will not affect the other array.

If you add a new element to either array, the other is unaffected.

Class array-like objects

The slice method can be used to convert an array-like object/collection into a new Array. You simply bind the method to the object. Arguments in a function is an example of an array-like object.

/ / the Denver nuggets: Lord which zha function list () {return Array. Prototype. Slice. The call (the arguments); } var list1 = list(1, 2, 3); / / [1, 2, 3]Copy the code

In addition to using Array. Prototype. Slice. The call (the arguments), you can simply use []. Slice. The call (the arguments) instead.

You can use bind to simplify the process

// Var unboundSlice = array.prototype. Slice; var slice = Function.prototype.call.bind(unboundSlice); function list() { return slice(arguments); } var list1 = list(1, 2, 3); / / [1, 2, 3]Copy the code

Ring data

Const obj = {foo: {name: 'foo', bar: {name: 'bar' baz: {name: 'baz', aChild: Null // let it point to obj.foo}}}} obj.foo.bar.baz.aChild = obj.foo // foo->bar->baz->aChild->foo forms a ring json.stringify (obj) // => TypeError: Converting circular structure to JSONCopy the code

Copying such a closed circular data structure leads to an infinite loop

What is deep copy and shallow copy

Shallow copy: copies the data in object A but does not copy the child objects in object A

Deep copy: clone an object with the same data, but with different reference addresses (copy the data in object A and copy its children)

Difference between shallow copy and deep copy

Recommendation: Can you implement a copy function using depth-first and breadth-first respectively? (6)

Uniapp realizes small program wechat login

Recommended: enterprise wechat open platform registration process

Recommended: UniApp to achieve small program wechat login

<button open-type="getUserInfo"/>
Copy the code

Add: app generates signature certificate

The ‘test’ in testAlias and test.keystore is modifiable and can be replaced with the name in your own project. To generate a certificate, enter the keytool -genkey command below

keytool -genkey -alias testalias -keyalg RSA -keysize 2048 -validity 36500 -keystore test.keystore
Copy the code

Use the signature generation tool to generate signatures

Uniapp mainfest.json file configuration, appID must start with ‘_UNI_’, so your configuration file should start with ‘_UNI_’.

Recommended: small program silent login scheme design

Recommended: Small program user login architecture design

Login solution

  • Cookie + SessionThe login
  • TokenThe login
  • SSOSingle sign-on (sso)
  • OAuthThird-party Login

SSO single sign-on (SSO) applies to medium – and large-sized enterprises that want to unify the login methods of all internal products.

Achieve vertical center

// Flex Margin: 0 autoCopy the code

How does Canvas scale full screen

  • document.documentElement.clientWidth: Visible area width;
  • document.documentElement.clientHeight: Height of the visible area.
  • canvas.width = document.documentElement.clientWidth
  • canvas.height = document.documentElement.clientHeight
  • screen.availWidth: Available screen width;
  • screen.availHeight: Screen visibility height.
  • Canvas. Width = screen. AvailWidth;
  • Canvas. Height = screen. AvailHeight;
  • Screen. width: display width of the screen
  • Screen. height: Display height of the screen
  • canvas.width = screen.width
  • canvas.height = screen.height
  • Window. innerWidth: The width of the window
  • Window. innerHeight: The height of the window
  • canvas.width = window.innerWidth
  • canvas.height = window.innerHeight

Vue2.0

Vue source root folder:

  • buildPackage related configuration files into different files according to different entry
  • distThe location of the file after packaging
  • examplesPart of the sample
  • flowBecause Vue is usedFlowTo perform static type checking, here is defined to declare some static types
  • packagesAnd generate the others, respectivelynpmpackage
  • srcWhere the main source code is located
  • compilerRelated files for template parsing
  • codegenAccording to theastgeneraterenderfunction
  • directivesGeneral generatedrenderThe instruction to be processed before the function
  • parserThe template parsing
  • coreThe core code
  • componentsGlobal components
  • global-apiThe global method
  • instanceInstance-related content, including instance methods, lifecycle, events, and so on
  • observerBidirectional data binding related files
  • utilUtility methods
  • vdomvirtualdomrelated
  • entriesThe entry file, which isbuildfolderconfig.jsImport file configured in
  • platformsPlatform related content
  • web.webEnd unique file
  • compilerInstructions and modules that need to be processed during compilation
  • runtimeComponents, instructions, and modules that need to be processed during the runtime
  • serverServer side rendering is relevant
  • utilTool library
  • weex.weexEnd unique file
  • sharedShared tool methods
  • testThe test case

View the Vue source from the entry file

First look at package.json file, which has project dependencies, startup scripts compiled by development environment, production environment, etc., license information of the project, etc. NPM run dev:

Rollup-w-c build/config.js --environment TARGET:web-full-devCopy the code

Rollup is a webpack-like packaging tool with entry files: / SRC /entries/ web-runtime-with-Compiler.js

/ / the Denver nuggets: / SRC /entries/web-runtime-with-compiler.js --> / SRC /entries/web-runtime.js --> / SRC /core/index.js --> /src/core/instance/index.jsCopy the code

Defining a Vue object’s constructor is extremely simple:

Function Vue (options) {if (process.env.node_env! == 'production' && ! (this instanceof Vue) warn('Vue is a constructor and should be called with the 'new' keyword') { } this._init(options) }Copy the code

Vue static and instance methods:

// src/core/index.js Vue.version = '__VERSION__' // src/entries/web-runtime-with-compiler.js Vue.compile = CompileToFunctions // convert template to render function // SRC /core/global-api // in directory structure, Vue static methods are mostly defined in this folder // SRC /core/global-api/index.js vue.config vue.util vue.set vue.delete vue.nexttick vue.options = { components: {KeepAlive: KeepAlive} directives: {}, filters: {}, _base: Vue } // src/core/global-api/use.js Vue.use // src/core/global-api/mixin.js Vue.mixin // src/core/global-api/extend.js Vue.extend // src/core/global-api/assets.js Vue.component Vue.directive Vue.filterCopy the code
Vm. _uid // the increased id vm._isVue // the identifier is a vue object, Avoid being observevm. _renderProxy // Proxy Proxy object vm._self // current VM instance vm.$parent // for custom subcomponents, $children // Array of subcomponent instances of the current component vm.$refs vm._watcher = NULL vm _isMounted = false // Determine whether vm._isDestroyed = false // Determine whether VM._isBeingDestroyed = False // Identifies whether vm._events is being destroyed // identifies whether the custom event vm._hasHookEvent bound to the current element has a hook: the event vm.$vnode // Vnode of the current custom component in the parent component, $options._parentVnode vm._vnode // Vnode vm._staticTrees // Render function array vm Vm.$slots // slots defined in the parent component is an object with the key name, $scopedSlots = emptyObject._c = (a, b, c, d) => createElement(vm, a, b, c, d); // When the user customizes the render method, $createElement = (a, b, c, d) => createElement(vm, a, b, c, d); True) vm._props // Object for storing props data vm._data // Object for storing data vM. _computedWatchers // Save the Watcher object created by the calculation attributeCopy the code

Hook functions:

  • beforeCreate, before creation
  • createdTo create
  • beforeMountAnd mount ago
  • mountedThe mount
  • beforeUpdateBefore, the update
  • updatedTo update
  • activatedTo trigger
  • deactivatedAnd stop using
  • beforeDestroyBefore, destroyed
  • destroyedAnd destroy
// vm.$options declare type ComponentOptions = { // data data: Object | Function | void; // The passed data props? : { [key: string]: PropOptions }; // props pass data propsData? :? Object; // For custom components, the parent passes data computed? Computing: {/ / incoming attribute key: string] : Function | {get? : Function; set? : Function; cache? : boolean } }; methods? : { [key: string]: Function }; // The incoming method watch? : { [key: string]: Function | string }; // Pass watch // DOM el? : string | Element; // The passed el string template? : string; Render: (h: () => VNode) => VNode; // Pass the render function renderError? : (h: () => VNode, err: Error) => VNode; staticRenderFns? : Array<() => VNode>; // The hook function beforeCreate? : Function; created? : Function; beforeMount? : Function; mounted? : Function; beforeUpdate? : Function; updated? : Function; activated? : Function; deactivated? : Function; beforeDestroy? : Function; destroyed? : Function; // assets directives? : { [key: string]: Object }; / / instructions components? : { [key: string]: Class<Component> }; // Define transitions for the child component? : { [key: string]: Object }; filters? : { [key: string]: Function }; // filter // context provide? : { [key: string | Symbol]: any } | () => { [key: string | Symbol]: any }; inject? : { [key: string]: string | Symbol } | Array<string>; // component v-model customization model? : { prop? : string; event? : string; }; // misc parent? : Component; // Parent component instance mixins? : Array<Object>; // Mixins pass data name? : string; // The current component name extends? : Class<Component> | Object; // extends passed data delimiters? : [string, string]; // Template delimiter // private property, both for internally creating custom component objects using _isComponent? : true; // Is it component _propKeys? : Array<string>; // props key array of the object passed _parentVnode? : VNode; // Current component, VNode object _parentListeners? :? Object; // Current component, event bound to parent component _renderChildren? :? Array<VNode>; // VNode array (slot) _componentTag:? string; // Custom label name _scopeId:? string; _base: Class<Component>; // Vue _parentElm: ? Node; // The parent dom node of the current custom component _refElm:? Node; // The nextSlibing element of the current element, i.e. the current DOM to be inserted before _refElm under _parentElm}Copy the code

To get the return type of a function, use TS

const func = (): number => 1; // Declare a generic type alias that returns the same value as the generic type. type Reverse<T> = (arg: any) => T; Function returnResultType<T>(arg: Reverse<T>): T {return {} as T; Const result = returnResultType((arg:any) => 3);} // returnResultType(arg:any); ResultType type ResultType = typeof result;Copy the code

Array

Constructor:

new Array() new Array(size) new Array(element0, element1, ... , elementn)Copy the code
  • sizeSet the number of array elements. Return array oflengthAttribute is equal to thesize.
  • Parameter list,element0,.. ,elementnwhenArray()When the constructor is called with these parameters, the newly created array instance is initialized with the specified parameter values and thelengthProperty to the number of arguments.
  • Called with no argumentsArray(), the returned array is empty,lengthThe property is 0.
  • concat()Joins elements into an array.
  • every(), tests whether the assertion function is true for every array element.
  • filter(), returns an array element that satisfies the assertion function.
  • forEach()Call the specified function for each element of the array.
  • indexOf(), looking for matching elements in the array.
  • join()Convert all the elements of the array to a string and concatenate them.
  • lastIndexOf()Reverse lookup in the array.
  • map()From the elements of the array, the new array element is computed.
  • pop()Removes the last element of the array.
  • push()Add the element to the end of the array.
  • reduce(), calculates a value from the elements of the array.
  • reduceRight()Shrinks the array from right to left.
  • reverse()Reverses the order of elements in the original array.
  • shift()Removes the first element of the array.
  • slice()Returns a portion of the array.
  • some(), tests whether there is at least one array element that makes the assertion function true.
  • sort(), sort the array elements in the original array.
  • splice()Insert, delete, or replace array elements.
  • toLocaleString()To convert an array to a local string.
  • toString()Convert an array to a string.
  • unshift()Inserts elements in the array header.

Array.concat()

array.concat(value, ...)
Copy the code

Return value, a new array, the element that contains the array, and the new element that joins.

Concat () concatenates arguments to an array to get a new array and returns it without modifying the array. If a parameter passed to concat() is itself an array, it concatenates elements of that array to the array, not the array itself.

Var a = [1, 2, 3]; A.c oncat (4, 5); / / [1, 2, 3, 4, 5];Copy the code

Array.every()Tests whether the assertion function is true for each element

array.every(predicate)
array.every(predicate,o)
Copy the code

Parameters:

  • Predicate, used to test predicate functions for array elements.

  • O, the optional this value when calling predicate.

Return value: True if true is returned when each element of the array is called, false if false is returned when any element of the predicate is called.

The every() method tests whether all elements of an array meet certain conditions. Every () returns true if each call to predicate returns true, otherwise, false.

Every () returns true when the array traversed is empty

[1,2,3]. Every (function(x) {return x<5; }) // true [1,2,3]. Every (function(x) {return x<3; }) // false [].every(function(x) {return false; }); // true [] always returns trueCopy the code

Array.filter()Returns an array element that passes an assertion

  • array.map(predicate)
  • array.map(predicate, o)
  • predicateUsed to judgearrayWhether the elements in the call function need to be included in the return array
  • o, the callpredicateAs optionalthisvalue

The return value:

A new array containing only the elements of the array that make predicate return true

Filter () creates a new array containing the elements of the array that make the predicate function return true. The filter() method does not modify the arrry itself, note that the predicate function may change.

Returns the newly created array.

Array.forEach()Calls a function for each array element

array.forEach(f)
array.forEach(f,o)
Copy the code

parameter

F is the optional this value when f is called by function O for each element of arrayCopy the code

Return value: This method does not return a value. Note that forEach() does not return a value. In particular, it does not return array.

ForEach (), map(), filter(), every(), some() accept functions as the first argument, and an optional second argument. In the body of the function, this is equal to o.

If no second argument is specified, this is a global object in non-strict mode and null in strict mode.

Var a = [1, 2, 3]; a.forEach(function(x,i,a){ a[i]++; }); / / / 2 and 4Copy the code

Array.indexOf()Find the array

array.indexOf(value)
array.indexOf(value,start)
Copy the code

Parameters:

Value Specifies the value to be searched in the array. Start Specifies the number of the optional array to be searched. If you omit it, the value is 0Copy the code

Index, or -1 if no matching element exists

The "===" operator ['a', 'b', 'c'].indexof ('b'); // 1 ['a', 'b', 'c'].indexOf('d', 1); / / 1Copy the code

Array.join()Concatenates array elements into strings

array.join()
array.join(separator)
Copy the code
  • separatorIn the returned string, the optional character or string used to separate one element of the array from the next element. If omitted, the default is the English comma.

Return value, a string.

A = new Array (1, 2, 3, "test"); s = a.join("+"); // 1+2+3+testCopy the code

Array.lastIndexOf()Reverse lookup array

array.lastIndexOf(value);
array.lastIndexOf(value,start);
Copy the code
  • valueinarrayThe value found in
  • start, the optional array ordinal to start the search, starting with the last element if omitted

Array.lengthThe array size

The length property represents the number of elements in the array

If length is greater than the original value, the array becomes larger, and the value of the element added to the end is undefined.

Array.map()Evaluates a new value from an array element

array.map(f);
array.map(f,o);
Copy the code
  • fThe function called for each element of the array whose return value becomes the element that returns the array.
  • ofOptional when calledthisValue.

Return value: a new array consisting of the elements evaluated by function f.

[1,2,3]. Map (function(x) {return x*x}); / /,4,9 [1]Copy the code

Array.pop()Removes and returns the last element of the array

array.pop()
Copy the code

Return value: The last element of array

Pop () removes the last element of the array, shortens the array, and returns the value of the removed element. If the array is already empty, pop() does not modify the array and returns undefined.

Pop () and push(), in and out of the stack:

var stack = []; / / stack: [] stack. Push (1, 2); // stack: [1,2] returns 2 stack.pop(); // stack: [1] returns 2 stack.push([4,5]); // stack: [1, [4,5]] returns 2 stack.pop(); // stack: [1] returns [4,5] stack.pop(); // stack: [] returns 1Copy the code

Array.push()Appends elements to an array

array.push(value,...) ;Copy the code

Return value: The new length of the array to which the specified value is appended. (It directly modifies the array rather than creating a new array.)

Push () and pop(), in and out of the stack function.

Array.reduce()Evaluates a value from an array element

array.reduce(f);
array.reduce(f,initial);
Copy the code
  • fA function that merges two values and returns a “reduced” new value.
  • initialTo reduce the optional initial value of the array. If this parameter is specified,reduce()Behavior like inserting the parameterarrayThe head is the same.

Return value: the reduced value of the array

Example:

[1, 2, 3, 4]. Reduce (function (x, y) {return x * y. }) / / 24Copy the code

Array.reduceRight()Shrink an array from right to left

array.reduceRight(f)
array.reduceRight(f, initial)
Copy the code
  • fA function that merges two values and returns a “reduced” new value.
  • initialUsed to reduce the optional initial value of the array. If specified,reduceRight()Behaves as if the parameter were insertedarayThe tail is the same.

Return value: The reduced value of the array that was returned when f was last called.

,10,60 [2]. ReduceRight (function (x, y) {return x/y; }) / / 3Copy the code

Array.reverse()Reverses the order of the elements in an array

array.reverse()
Copy the code

The Reverse () method of the Array object reverses the order of Array elements. Instead of creating a new array, it operates on the original array.

A = new Array (1, 2, 3); a.reverse();Copy the code

Array.shift()Removes the first element of the array

array.shift()
Copy the code

Return value: the original first element of the array.

If the array is empty, shift() does nothing, returns undefined and does not create a new array.

Var a = [1, 2, 3], 4]. a.shift(); / / 1Copy the code

Array.slice()Returns part of an array

array.slice(start, end)
Copy the code

Return value: a new array containing all elements in the array from start to end (including elements specified by start, but not elements specified by end). If end is not specified, the returned array contains all elements from start to the end of the array.

Var a = [1, 2, 3, 4, 5]. A.s lice (0, 3); // return [1,2,3] a.ice (3); / / return [4, 5)Copy the code

Array.some()Tests whether any element satisfies the assertion function

array.some(predicate)
array.some(predicate,o)
Copy the code
  • predicateAn assertion function used to test array elements
  • ocallpredicateAs optionalthisvalue

Return value: True if at least one element in the array returns true when called from predicate, false if all elements return false when called from predicate.

[1, 2, 3]. Some (function (x) {return x > 5; }); //false [1,2]. Some (function(x) {return x>2; }); // true [].some(function(x) { return false; }); // falseCopy the code

Array.sort()Sort array elements

array.sort()
array.sort(orderfunc)
Copy the code
  • orderfuncAn optional function to specify how to sort

Return value: a reference to the array. Notice we’re sorting in the old array, no new key array. Undefined elements in an array are always arranged at the end of the array.

function numberorder(a,b) {return a-b; } a = new Array(3,2,4); a.sort(); // alphanumeric sort a.ort (numberOrder); // Numeric sortCopy the code

Array.splice()Inserts, removes, or replaces array elements

array.splice(start,deleteCount,value,...)
Copy the code
  • startThe sequence number of the array element at the beginning of insertion and deletion.
  • deleteCountNumber of elements to be deleted fromstartStart and containstartIf 0 is specified, the element is inserted without deleting any elements.
  • value,...To insert zero or more values in the array fromstartThe serial number starts to insert.

The return value:

If elements are removed from the array, a new array is returned containing the deleted elements, and splice() directly modifies the array.

Var a = [6]. A.s plice (1, 2);Copy the code

Array.toLocaleString()Converts an array to a local string

array.toLocaleString()
Copy the code

Return value: localized string representation of the array. (Exception, thrown if the object is not an array when called.)

Array.toString()Convert an array to a string

array.toString()
Copy the code

Return value: string representation of array. (Exception, thrown if the object is not an array when called.)

Array.unshift()Inserts elements in the array header

array.unshift(value,...)
Copy the code

Parameters: the value,… To insert one or more values in the array header.

Return value: The new length of the array. Unshift () does not create a new array, but modifies the array itself.

var a = [];
a.unshift(1); // a:[1];
Copy the code

BooleanSupport for Boolean values

Constructor:

Boolean(value) // Constructor Boolean(value) // Conversion functionCopy the code

Parameter: value, Boolean Specifies the value stored in the object, or the value to be converted to a Boolean value.

  • Boolean()Converts the argument to a Boolean value and returns a value containing the valueBooleanObject.
  • 0,NaN,null, empty string "" and undefinedIt will all be changed to false.
  • toString()According to theBooleanObject represents a Boolean value"True" or "false"A string.
  • valueOf()returnBooleanObject containing the original Boolean value.
  • BooleanObject is an object that encapsulates a Boolean value.

Boolean. ToString, converts a Boolean value to a string

b.toString()
Copy the code
  • When this method is called, an exception is thrown if the object is not of Boolean type.

Boolean. ValueOf (), Boolean specifies the Boolean valueOf the object

Date Date and time of the operation

new Date()
new Date(milliseconds)
new Date(datestring)
new Date(year, month, day, hours, minutes, seconds, ms)
Copy the code

Without arguments, the Date() constructor creates a Date object based on the current Date and time.

Date.getdate () returns the Date value in the month of a Date object

Return: Given the Date value in the month of the Date object, use the local time. The value ranges from 1 to 31

Date.getday (), return values 0(Sunday) to 6(Monday)

Date.getfullyear (), which returns a full 4-digit year

Date.gethours (), returns the hour value of a Date object, from 0 to 23

Date.getmilliseconds (), which returns the milliseconds of a Date object

Date.getminutes (), which returns the minute value of a Date object between 0 and 59

Date.getmonth (), which returns the month value of a Date object between 0(January) and 11(December)

Date.getseconds (), which returns the value of a Date object in seconds between 0 and 59

Date.gettime (), which returns a Date object in milliseconds

Date.getyear (), returns the year value of a Date object

Date.now(), returns the current time in milliseconds

Date.parse(), which parses a Date or time string

Date.setdate () sets the January Date value of a Date object

Date.setfullyear () sets the year value of a Date

Date.sethours () sets the hour, minute, second and millisecond values of a Date

Date.setmilliseconds () sets the milliseconds value of a Date

Date.setminutes () sets the minute, second, and millisecond values of a Date

Date.setmonth () sets the month and value of a Date

Date.setseconds () sets the seconds and milliseconds of a Date

Date.settime () sets a time using the millisecond value

Date.setyear () sets the year value of a Date

DecodeURI () section decodeURI a character in a URI

DecodeURI (uri) // URI A string containing the encoded URI or other text to be decodedCopy the code

EncodeURI () escapes a character in a URI

Escape a character in a URI

The Function Function

// Constructor new Function(argument_names... , body) // arguments_names... Any number of string arguments // body specifies a string in the body of the Function. // returns the newly created Function object. // exception SyntaxError indicates a JavaScript SyntaxError in the body argument or one of the argument_names argumentsCopy the code

attribute

Arguments [] specifies the array of arguments passed to a Function. It is not recommended to use a reference to the Function object that calls the Function as callerCopy the code

Methods:

Apply () calls the function as a method on the specified object. It is passed the specified array of parameters. Bind () returns a new function. Call () calls the function as a method on the specified object. It is passed the specified arguments. ToString () returns a string representation of the function.Copy the code

Function.apply()

Function. Apply (if this is null, use the global object, an array of values) // Return the value returned by calling function. Or args is not an array and Arguments object and raises an exceptionCopy the code

Example:

Object.prototype.toString.apply(o); Var data =,2,3,4,5,34 [1]; Math.max.apply(null,data);Copy the code

Function.bind(), which returns a Function called as a method

function.bind(o) function.bind(o,args...) // o Object to bind to function // args... Zero or more parameter values to bind to a function // returns a new functionCopy the code

Example:

Var g = f.box (o, 1,2); F. all (o, 1, 2, 3);Copy the code

Function.arguments[] Arguments passed to functions. Use is not recommended

Function.call() calls a Function as a method of an object

function.call(thisobj, args...) // thisobj is the object that calls function. In the body of the function, thisobj is the value of this keyword. If this parameter is null, the global object is used. Any number of arguments // returns the value returned by calling functionCopy the code

Example:

Object.prototype.toString().call(o);
Copy the code

Function.caller() calls functions of the current Function. This property is not required and should not be used

Function.length() Specifies the number of arguments to declare

Function.prototype() Specifies the object class prototype

Function.tostring () converts a Function to a string

Returns: a string representing the function

Global object

Global properties

The global object is not a class. Note that all global variables are also properties of the global object:

  • InfinityA number representing positive infinity
  • NaNRepresents a value that is not numerical
  • undefinedsaidundefinedvalue

Global function

  • decodeURI()Decoding usingencodeURI()Escaped string
  • decodeURIComponent()Decoding usingencodeURIComponent()Escaped string
  • encodeURI()Encode urIs by escaping specific characters
  • encodeURIComponent()Encoding parts of a URI by escaping specific characters
  • escape()Encodes a string by replacing specific characters with an escape sequence
  • eval()Executes the JavaScript code string and returns the result
  • isFinite()Determines whether a value is infinite
  • isNaN()Determines whether a value is non-numeric
  • parseFloat()Parse numeric values from strings
  • parseInt()Parsing integers from strings
  • unescape()Decoding usingescape()Encoded string

Global object

  • Array
  • Boolean
  • Date
  • Error
  • EvalError
  • Function
  • JSON
  • Math
  • Number
  • Object
  • String
  • TypeError
  • URIError

NaN non-numeric attributes

NaN is a global property that points to a special non-numeric value. NaN attributes are not enumerable with a for/in loop and cannot be deleted with the DELETE operator. NaN is not a constant and cannot be set to any other value.

To check if a value is a number, use isNaN(). NaN is always not equal to other values, nor is it equal to itself.

Object is a superclass that contains the features of all JavaScript objects

new Object()
new Object(value)
Copy the code

Attribute: constructor, referring to the current object’s constructor.

Methods:

  • hasOwnProperty()

Checks whether the object has a locally defined property with the specified name

  • isPrototypeOf()

Checks whether the current object is the prototype of the specified object

  • propertyIsEnumerable()

Checks if the property with the specified name exists and can be enumerated with a for/in loop

  • toLocaleString()

Returns a localized string representation of the object

  • toString()

Returns a string representation of the object

  • valueOf()

Returns the original value of the current object, if any.

Static method:

  • Object.create()

Creates a new object with the specified stereotype and properties

  • Object.defineProperties()

Creates or configures one or more properties of the specified object

  • Object.defineProperty()

Creates or configures an attribute of the specified object

  • Object.freeze()

Sets the specified object to immutable

  • Object.getOwnPropertyDescriptor()

Queries the properties of the specified property of the specified object

  • Object.getOwnPropertyNames()

Returns an array to be given containing all non-inherited property names of the specified object, containing non-enumerable properties

  • Object.getPrototypeOf()

Returns the prototype of the specified object

  • Object.isExtensible()

Checks whether the current object can be added to the new property

  • Object.isFrozen()

Check whether the current object is frozen

  • Object.isSealed()

Checks whether the specified object is closed

  • Object.keys()

Returns an array containing all non-inherited enumerable property names of the specified object

  • Object.preventExtensions()

Prevents new attributes from being added to the specified object

  • Object.seal()

Prevents new attributes from being added to the specified object or existing attributes from being deleted

The Object class is a built-in data type in the JavaScript language. It is the superclass of all other JavaScript objects, so all methods and behaviors of the Object class are inherited by other objects.

Constructor The constructor of an Object

The constructor property of all objects points to the function used as the current object’s constructor. If we use the Array() constructor to create an Array a, then a.constructor is an Array:

A = new Array (1, 2, 3); // Create an object a.constructor == Array // the value is trueCopy the code

Check if it is an array:

function isArray(x) {
 return ((typeof x == "object") && (x.constructor == Array));
}
Copy the code

The constructor attribute is often used to detect the type of an unknown object. Given an unknown value, you can use the Typeof operator to check whether it is a primitive value or an object.

If it is an object, you can use the constructor property to check the object’s type.

Object.create() creates an Object with the specified stereotype and properties

Object.create(proto)
Object.create(proto,descriptors)
Copy the code

Parameters:

// proto The prototype of the newly created object, which can be null // Descriptors an optional object that maps the attribute name to the attribute descriptor // Return a newly created object, inherited from Proto, and owning the attributes described by DescriptiorsCopy the code

Example:

Var p = object. create({z:0},{x: {value:1,writable: false, Enumerable: true, different: 64x) {// Create a new Object with x and x attributes. true}, y: {value:2,writable: false, enumerable: true, configurable: true}, });Copy the code

Object.defineProperties();

Create or configure multiple properties of the object

// o The object on which attributes are to be created or configured // Descriptors the object on which attribute names are mapped to attribute descriptors // returns object OCopy the code

Example:

Var p = object.defineProperties ({},{x: {value:1,writable: false, Enumerable: true, different: true}, y: {value:2,writable: false, enumerable: true, configurable: true}, });Copy the code

Object.defineProperty()

Creates or configures a property of the object

Object.defineProperty(o, name, desc)
Copy the code

Parameters:

// o The object on which properties will be created or configured // name The name of the property to be created or configured // desc a property descriptor object describing a new property to be created or a modification of an existing property // Returns the object OCopy the code

Example:

DefineProperty (o, n, {value: v, writable: false, enumerable: true, configurable: false}); }Copy the code

Object.freeze()

To set an object to be immutable, freezing an object is a permanent operation. Once frozen, it cannot be unfrozen. Object.freeze() sets only the writable properties of data properties, those properties that have corresponding setter functions are not affected, and Object.freeze() does not affect inherited properties.

Object.getOwnPropertyDescriptor()

Query the properties of an attribute

Object.getOwnPropertyDescriptor(o,name)
Copy the code

Parameters:

// o Object whose properties are to be queried // name Name of the properties to be queried // Returns an attribute descriptor object of the specified properties of the specified object, undefined if no specified properties exist. // Description An attribute descriptor is an object that describes the properties and values of the propertyCopy the code

A data attribute has a value and three properties:

  1. The enumerated type
  2. Read/write type
  3. configurability

Accessor properties have a getter and setter methods, as well as enumerability and configurability.

Descriptors for data attributes:

{
 value:
 writable:
 enumerable:
 configurable:
}
Copy the code

Accessor property descriptor:

{
 get:
 set:
 enumerable:
 configurable:
}
Copy the code

Object.getOwnPropertyNames()

Returns the name of a non-inherited property

Object.getOwnPropertyNames(o); // o An objectCopy the code

Returns an array of o with the names of non-inherited properties, including those that are not enumerable

Object. GetOwnPropertyNames ([]) / / / "length" : "length" cannot be enumeratedCopy the code

Object.getPrototypeOf()

Returns the prototype of an object

Var p = {}, // a primitive object.getProtoTypeof (p); // Object.prototype var o = Object.create(p); // An Object that inherits p object.getProtoTypeof (o); // pCopy the code

Object.hasOwnProperty()

Checks if an attribute is inherited

Example:

var o = new Object(); // Create an object. X = 3.14; // Define a non-inherited local property, O.hasownProperty ("x"); // Return true, x is the local property of o, o.hownProperty ("y"); // false, o has no property y o.hasownProperty ("toString"); // Returns false, which is an inherited propertyCopy the code

Object.isExtensible()

Determines whether new attributes can be added to an object

Example:

var o = {}; // Create a new Object object.isextensible (o); // true, it is object.preventExtensions (o); // Set it to Object.isextensible (o); // falseCopy the code

Object.isfrozen () Checks whether an Object is immutable

  • An object is frozen if all of its non-inherited properties are read-only, or if it is closed
  • An object is said to be closed if new attributes can be added to it and existing attributes cannot be deleted
  • Object.isfrozen () checks whether its parameters are frozen
  • Once an object is frozen, it cannot be defrosted

Object.isprototypeof () determines whether the current Object is a prototype of another Object

  • Return true if object is a prototype of O, false if O is not an object, or Object is not a prototype of O.
var o = new Object(); Object.prototype.isPrototypeOf(o); / / true: o is an object Function. The prototype. IsPrototypeOf (o.t oString); / / true, toString Array) is a function prototype. IsPrototypeOf ([1, 2, 3]); // true o.constructor == Object // trueCopy the code

Object.issealed () Determines whether properties of an Object can be added or deleted

  • Once an object is closed, there is no way to unseal it
  • Seal an Object: Object.seal() or object.freeze ()

Object.keys() returns its own enumerable property name

Object.keys({x:1,y:2}); // ["x","y"]
Copy the code

Object.preventExtensions()

Disallows adding new attributes to an object

  • Object.preventextensions () sets o’s extensibility to false and will not be able to add new properties to it
  • This is a permanent change

Object.propertyIsEnumerable()

Checks if an attribute is visible in a for/ IN loop

var o = new Object();
o.x=12;
o.propertyIsEnumerable("x"); // true
o.propertyIsEnumerable("y"); // false
o.propertyIsEnumerable("toString"); // false
Copy the code

Object.seal() prevents adding or deleting attributes of an Object

Object.tolocalestring () returns a localized string representation of the Object

Object.tostring () defines the string representation of an Object

Object.valueof () specifies the original valueOf the given Object

ParseFloat () converts a string to a number

ParseInt () converts a string to an integer

String() A String is supported

Methods:

  • charAt()

Retrieves a character at the specified position in a string

  • charCodeAt()

Returns the encoding of a character at a specified position in a string

  • concat()

Concatenate one or more values into a string

  • indexOf()

Finds a character or string in the specified string

  • lastIndexOf()

Finds a character or string backwards in the specified string

  • localCompare()

Compares strings in a locally defined order

  • replace()

Use regular expressions to perform find and replace operations

  • search()

Finds a string in a string that matches a regular expression

  • slice()

Returns a slice or substring of a string

  • split()

Breaks a string into an array of strings at the specified delimiter string or regular expression

  • substr()

Extract a string of strings, a variant of subString()

  • substring()

Extracts a string of strings

  • toString()

Returns the original string value

  • valueOf()

Returns the original string value

Go back to my previous articles and you may get more!

  • TypeScript learns early to become competitive in the workplace
  • A qualified junior front-end engineer needs to master module notes
  • More than 234.77 million words in front-end simulation interview
  • Vue.js pen test questions Solve common business problems
  • [Primary] Personally share notes of Vue front-end development tutorial
  • A long summary of JavaScript to consolidate the front end foundation
  • ES6 comprehensive summary
  • Dada front-end personal Web share 92 JavaScript interview questions with additional answers
  • [Illustrated, like collection oh!] Re-study to reinforce your Vuejs knowledge
  • 【 Mind Mapping 】 Front-end development – consolidate your JavaScript knowledge
  • 14 – even liver 7 nights, summed up the computer network knowledge point! (66 items in total)
  • This was my first JavaScript primer
  • LocalStorage and sessionStorage localStorage
  • Drag and drop in HTML5
  • Challenge the front-end HTTP/ECMAScript
  • Must learn must learn – Audio and video
  • 170 Interview questions + answer Learn to organize (conscience making)
  • Front-end HTML5 interviewers and candidates ask and answer questions
  • Ne Zha is sweeping the sea
  • Tencent location service development applications
  • [Advanced] The interviewer asked me how Chrome renders (6000 words)
  • The interviewer started by asking me about Chrome’s underlying principles and HTTP protocol (swastika)
  • Staying up late summed up the “HTML5 Canvas”
  • This /call/apply/bind
  • The HTTP/HTTPS/HTTP2 / DNS/TCP/classic problem
  • Execute context/scope chain/closure/first-class citizen
  • Web page creation basics
  • Learn the summary of HTML5 finger front-end (suggested collection, illustrated)

❤️ follow + like + Favorite + comment + forward ❤️

Likes, favorites and comments

I’m Jeskson, thanks for your talent: likes, favorites and comments, and we’ll see you next time! ☞ Thank you for learning with me.

See you next time!

This article is constantly updated. You can search “Programmer Doraemon” on wechat to read it for the first time, and reply [information] there are materials of first-line big factories prepared by me, which have been included in this article www.dadaqianduan.cn/#/

Star: github.com/webVueBlog/…