Compile javascript interview questions
JavaScript Object-oriented & inheritance
- Reference: JavaScript Object-oriented & Inheritance
Prototypes and prototype chains
- Reference: Easy to understand Javacsript prototypes and prototype chains
Closures and exercises
- Reference: Javascript closures in detail
Function throttling and shaking
- Reference: Function throttling and shaking
Javascript in this
- Reference: this (include apply, call, bind)
Implement apply, Call, bind
- Reference: hands-on implementation apply, call, bind
Javascript hacks can help you improve your code
- Reference: 12 Javascript Hacks to improve your code
Make promises happen yourself
- Reference: Make promises happen yourself
Scope & Scope chain
- Simply put, scope is the accessible scope of variables and functions, that is, the scope controls the visibility and life cycle of variables and functions. A scope is a set of rules that lookup variables by identifier name in the current scope and in nested child scopes.
- The function of the scope chain is to ensure that the variables and functions that can be accessed in the execution environment are ordered. Variables in the scope chain can only be accessed upwards. If a variable accesses the Window object, it will be terminated.
What exactly does the new operator do
- Create an empty object
- Inherits the prototype of the function
- Properties and methods are added to the object referenced by this
- The newly created object is referenced by this, and this is implicitly returned
Strict mode restrictions
- Variables must be declared before they are used
- Function arguments must not have attributes of the same name, otherwise an error will be reported
- You cannot use the with statement
- Cannot assign a value to a read-only attribute, otherwise an error is reported
- The prefix 0 cannot be used to indicate octal, otherwise an error will be reported
- Undeletable properties cannot be deleted, otherwise an error is reported
- Delete global[prop] delete global[prop]
- Eval does not introduce variables in its outer scope
- Eval and arguments cannot be reassigned
- Arguments do not automatically reflect function argument changes
- You cannot use arguments.callee
- You cannot use arguments.caller
- Disallow this to point to global objects
- You cannot use fn.caller and fn.arguments to get the stack of function calls
- Added reserved words (such as protected, static, and interface)
Es6 new features
- let const
- Method extensions for strings, arrays, and objects
- New data types and data structures for symbol, set, map
- Proxy interception
- Asynchronous solutions: Promise, generate, async, await
- Class class
- The module module
Details can refer to: ES6 introduction tutorial – Ruan Yifeng
Object oriented programming & Procedure oriented programming
Concept:
- Process-oriented is to analyze the steps needed to solve the problem, and then use the function to implement these steps step by step, when using one call in turn can be;
- Object orientation is the decomposition of the problem constituting transactions into objects, the purpose of the object is not to complete a step, but to describe the behavior of something in the whole problem solving step. Object orientation divides problems in terms of functionality, not steps. Object – oriented programming uses objects, classes, inheritance, encapsulation and other basic concepts.
The advantages and disadvantages:
- Process-oriented:
- Advantages: Higher performance than object-oriented, because class invocation needs to be instantiated, more overhead, more consumption of resources; For example, embedded development, Linux/Unix, etc. are generally process-oriented, and performance is an important factor.
- Disadvantages: No object oriented easy to maintain, easy to reuse, easy to extend
- object-oriented
- advantages: High readability, easy to maintain, easy to reuse, easy to expand, due to the object-oriented encapsulation, inheritance, polymorphism characteristics, can design a low coupling system, make the system more flexible, easier to maintain.
- Easy maintenance: Each developer only needs to maintain the definition and extension of the function fields and methods of the class he or she is responsible for.
- Reusable: Objects are independent of each other, and there is little coupling between functions and objects.
- Easy to extend: Objects’ attributes and methods are extensible.
- Disadvantages: Class invocation requires instantiation, high overhead, lower performance than procedure oriented
The difference between an arrow function and an ordinary function
- The this object in the body of the function is the object that was defined, not the object that was used
- It cannot be used as a constructor, that is, it cannot use the new command, otherwise an error will be thrown
- Do not use the Arguments object. It does not exist in the function body. If so, use the Rest parameter instead
- You cannot use the yield command, so arrow functions cannot be used as Generator functions
The implementation of asynchronous programming
- The callback function
Pros: simple, easy to understand Cons: poor maintenance, high code coupling
- Event listening (in time-driven mode, depending on whether an event occurred)
Advantages: easy to understand, multiple events can be bound, and each event can specify multiple callback functions Disadvantages: event-driven, process not clear
- Publish/Subscribe (Observer pattern)
It is similar to event listening, but you can see how many publishers and subscribers there are through the ‘message center’. Promise object benefits: You can use the THEN method to write the chain; You can write an error callback function; Cons: Relatively difficult to write and understand
- The Generator function
Advantages: data exchange inside and outside the function, error handling mechanism Disadvantages: process management is not convenient
- Async function
Advantages: Built-in actuator, better semantics, wider applicability, Promise returned, clear structure. Disadvantages: Error handling mechanism
Event loop & macro task, micro task
Macrotask: macrotask also known as task microtask: microtask also known as jobs
Micro tasks
- process.nextTick (Node)
- promise
- Object.observe
- MutationObserver (browser)
Macro task
- script
- setTimeout
- setInterval
- setImmediate
- I/O
- UI rendering
- Callback functions (events, Ajax, and so on)
In an event loop, the main task of the JS thread will be executed first, and then it will look for microtask (Promise). If there are microtasks, it will be executed first. If there are no microtasks, it will look for macroTask (setTimeout, setInterval) to execute.
The execution steps of an event loop:
- Execute the synchronization code, which is a macro task
- Perform all microtasks
- Render the UI if necessary
- The next Event loop is started, executing the asynchronous code in the macro task
In an event loop, the microtask executes before the macro task, so even if the code in the new Promise () executes immediately after the code in setTimeout(() => {}, 0), it executes ahead of time.
setTimeout(() = > console.log(1), 0);
new Promise((resolve) = > resolve(' '), () = > {})
.then(() = > {
console.log(2);
setTimeout(() = > console.log(4), 0);
new Promise((resolve) = > resolve(' '), () = > {}).then(() = > console.log(3))});// Result: 2 3 1 4
Copy the code
Javascript Garbage Collection
- Mark and sweep
- This is the most common form of garbage collection in JavaScript. When a variable enters the execution environment, such as when a variable is declared in a function, the garbage collector marks it as “in,” and when the variable leaves the environment (at the end of the function’s execution), the garbage collector marks it as “out.”
- At runtime, the garbage collector marks all variables stored in memory, and then removes variables in the environment and variables referenced by the environment variables (closures). Variables that remain marked after this is done are those to be deleted
- Reference Counting
- Memory leaks often occur in older versions of IE, often because of reference counting for garbage collection.
- The strategy for reference counting is to keep track of how many times each value is used.
- When a variable is declared and a reference type is assigned to it, the number of references to that value is increased by one
- If the value of this variable changes to another, then the number of times this variable is worth referencing is reduced by one,
- When the number of references to this value goes to 0, it means that no variable is in use and the value can no longer be accessed. Therefore, the space occupied by this value can be reclaimed. In this way, the garbage collector will clean up the space occupied by the value with the number of references to 0 at runtime
Depth copy
Shallow copy: Copy only the first layer
Object.assign
.- Expansion operator
.
Parse (json.stringify (object))
- Ignores undefined
- Ignore the symbol
- Cannot serialize function
- Objects with circular references cannot be resolved
Processes and Threads
Essentially, processes and threads are a description of the CPU’s time slice.
- A process describes how long it takes the CPU to run instructions and load and save the context. In the case of an application, a process represents a program.
- Threads are smaller units in a process that describe the time it takes to execute a single instruction.
When you open a Tab page, you create a process. A process can have multiple threads, such as rendering threads, JS engine threads, HTTP request threads, and so on. When you make a request, you create a thread that may be destroyed when the request ends.
Benefits of single threading: As mentioned above, the JS engine thread and the render thread can block UI rendering while JS is running. This means that the two threads are mutually exclusive. The reason for this is that JS can modify the DOM, and if the UI thread is still working while JS is executing, it may not render the UI safely. This is also a single thread benefits, because JS is run in a single thread, can achieve memory savings, save context switch time, no lock problems benefits
ajax
function ajaxGet(url, params, success, fail) {
// 1. Create connection
var xhr = null;
xhr = new XMLHttpRequest()
// 2. Connect the server
xhr.open('get', url + encodeParams(params), true)
// 3. Send a request
xhr.send(null);
// 4. Accept the request
xhr.onreadystatechange = function(){
if(xhr.readyState == 4) {if((xhr.status >= 200 && xhr.status < 300) || xhr.status === 304){
success(xhr.responseText);
} else{ fail && fail(xhr.status); }}}function encodeParams(obj){
return Object
.keys(obj)
.map(function(key) {return encodeURIConponent(key) + '=' +encodeURIConponent(obj[key]})
.join('&'); }}function ajaxPost(url, params, success, fail) {
// 1. Create connection
var xhr = null;
xhr = new XMLHttpRequest()
// 2. Accept the request
xhr.onreadystatechange = function(){
if(xhr.readyState == 4) {if((xhr.status >= 200 && xhr.status < 300) || xhr.status === 304){
success(xhr.responseText);
} else{ fail && fail(xhr.status); }}}// 3. Connect the server
xhr.open('post', url, true)
// 4. Send a request
xhr.send(JSON.stringify(params));
}
Copy the code
Regular expressions
How does jQuery extend custom methods
jQuery.fn.myMethod = function () {
alert('myMethod');
};
/ / or:
jQuery.fn.extend({
myMethod: function () {
alert('myMethod'); }});/ / use:
$("#div").myMethod();
Copy the code
Event delegation
Binding the event to the parent node reduces the number of DOM event bindings by getting the leaf node that was actually clicked because of the event bubble.
document.body.addEventListener('click'.e= > console.log(e));
/* {currentTarget: null; /* {currentTarget: null; Target: h1#title.title // Click on the bottom leaf} */
Copy the code
Why currentTarget is null:
- This is due to console’s mechanism for logging an object. Log does not contain all the properties of an object; it only contains references to the object. When you click expand, it will find you the properties of that object.
- The currentTarget property has a value when console.log(e) is called, but the value is then reset to null. So when you expand the event object, you see null.
§ typescript
TypeScript is a free, open source programming language developed and maintained by Microsoft. It is a strongly typed JavaScript superset that currently does not run directly in a browser environment and can be compiled to pure JavaScript for execution.
TypeScript can be thought of as an optimized version of Javascript that takes the best from the bad, while retaining the relative freedom of a dynamic language and the lack of compile type checking that makes it unsuitable for very large projects.
Use TS scenarios: TypeScript has better type checking, but it also limits the flexibility of JS to some extent. Therefore, we should use JS for daily development of relatively independent business requirements, and TS for large, collaboratively multi-person, logically complex projects.
- Reference: getting Started with TypeScript
](ts.xcatliu.com/)
Ts and JS detailed comparison
JavaScript | TypeScript | |
---|---|---|
1 | It was developed by Netscape in 1995. | It was developed by Anders Hejlsberg in 2012. |
2 | JavaScript source files in “. Js “extension. | TypeScript source files have the.ts extension. |
3 | JavaScript does not support ES6. | TypeScript supports ES6. |
4 | It does not support strong typing or static typing. | It supports strong typing or static typing. |
5 | It’s just a scripting language. | It supports object-oriented programming concepts such as classes, interfaces, inheritance, generics, and so on. |
6 | JavaScript has no optional parameter feature. | TypeScript has optional arguments. |
7 | It’s an interpreted language, which is why it highlights errors at run time. | It compiles the code and highlights errors during development. |
8 | JavaScript does not support modules. | TypeScript supports modules. |
9 | In this case, number and string are objects. | In this case, number and String are interfaces. |
10 | JavaScript does not support generics. | TypeScript supports generics. |
Object-oriented: three characteristics: “encapsulation,” “polymorphism”, “inheritance”, five principles: “single responsibility principle”, “open closed principle”, “Richter substitution principle”, “dependency inversion principle”, “interface separation principle”, “Demitt principle (high cohesion and low coupling)”
- The module
- class
- interface
- inheritance
- encapsulation
- polymorphism
- The data type
Ts Installation and use
Install typescript globally
npm install -g typescript
After installing TS, a command line tool "TSC" is automatically installed, which will be used to compile ts code to generate JS files.
tsc helloworld.ts
# Real-time hot update compilation
tsc --watch helloworld.ts
# ts source debugging
tsc -sourcemap helloworld.ts
Copy the code
The difference between interface and type
1. Interface Interface definition: Type check the structure of the value. Function: Defines data type specifications for type naming and third-party code.
2. Type Type alias
What it does: Gives the type a new name.
3. Type is ok but interface is not
- Type can declare basic type aliases, union types, tuples, etc. Classes and interfaces cannot (only describe objects and functions).
- The type statement can also use typeof to get the typeof the instance for assignment
4. Interface works but type does not
- Interfaces can declare merges (if interfaces have the same name, take a union)
5. Both interface and type are acceptable
- Both can be used to describe the type of an object or function, but the syntax is different.
/ / interface
interface Point {
x: number;
y: number;
}
interface SetPoint {
(x: number.y: number) :void;
}
// Type alias
type Point = {
x: number;
y: number;
};
type SetPoint = (x: number, y: number) = > void;
Copy the code
- Both can be extended, but the syntax is different
Type aliases cannot inherit from other type aliases or interfaces, nor can they be inherited.
// Extend from interface to interface
interface PartialPointX { x: number; }
interface Point extends PartialPointX { y: number; }
// Extend from type to type
type PartialPointX = { x: number; };
type Point = PartialPointX & { y: number; };
// Extension from type to interface
type PartialPointX = { x: number; };
interface Point extends PartialPointX { y: number; }
// Extension from interface to type
interface PartialPointX { x: number; }
type Point = PartialPointX & { y: number; };
Copy the code
6. Finally, if it is not clear when to use interface/type, use interface, if not, use type.
tuples
A ts array merges objects of the same type, while a Tuple merges objects of different types.
The java.js array itself contains a meta-property that supports multiple types of arrays.
let tom: [string.number] = ['Tom'.25];
Copy the code
The enumeration
Enumeration (Enum) Type This parameter is used when the value is limited to a certain range. For example, the value can be only seven days in a week, and the color can be red, green, and blue.
- Enumeration members are assigned numbers increasing from 0, and the enumeration value is inversely mapped to the enumeration name
- You can assign values to enumerations manually
enum Days {Sun, Mon = 1, Tue, Wed, Thu, Fri, Sat};
console.log(Days["Sun"= = =0); // true
console.log(Days[0= = ="Sun"); // true
Days[Days["Sun"] = 0] = "Sun";
console.log(Days["Sun"= = =7); // true Manual assignment
Copy the code
paradigm
Generics is a feature that defines a function, interface, or class without specifying a specific type in advance, but instead specifies the type when it is used.
- Reference: TypeScript Introduction – Generics
// You can specify a default type: T = string
function createArray<T = string> (length: number, value: T) :Array<T> {
let result: T[] = [];
for (let i = 0; i < length; i++) {
result[i] = value;
}
return result;
}
createArray<string> (3.'x'); // ['x', 'x', 'x']
createArray(3.'x'); // You can also infer types automatically
Copy the code
§ When more than one type parameter defines a generic type, you can define more than one type parameter at a time using a meta-ancestor:
function swap<T.U> (tuple: [T, U]) :U.T] {
return [tuple[1], tuple[0]];
}
swap([7.'seven']); // ['seven', 7]
Copy the code
§ Generic constraint When using a generic variable within a function, you cannot arbitrarily manipulate its properties or methods without knowing what type it is
In this case, the generics can be constrained to allow the function to pass only those variables that contain the length attribute. This is the generic constraint:
interface Lengthwise {
length: number;
}
function loggingIdentity<T extends Lengthwise> (arg: T) :T {
console.log(arg.length);
return arg;
}
Copy the code
The enumeration
enum statusCode{
ok=0,
error=1,
pedding=2
}
statusCode[0= = ='ok'
statusCode['ok'= = =0
Copy the code
Poses used with vuE2 and VUE3
§ vue2 + ts
- Reference: Vue2 + TypeScript Best Practices for getting Started
The SRC directory has two additional files:
shims-tsx.d.ts
Allows you to write JSX code in a Vue project from a.tsx ending fileshims-vue.d.ts
Vue files are not supported by Ts by default. This file tells Ts to import.vue files as VueConstructor.
§ How to write a vue2 + typescript component
<script lang="ts">
import { Component, Prop, Vue } from 'vue-property-decorator';
@Component({
name: 'HelloWorld'.components:{ componentA, componentB},
})
export default class HelloWorld extends Vue {
// The component property props
@Prop({ default: 'default value'}) private msg! : string;// Component data
private test: { value: string }
// Calculate the properties
private get reversedMessage (): string[] {
return this.message.split(' ').reverse().join(' ')}// Listen for data change (onMsgChanged)
@Watch('child')
onMsgChanged(val: string, oldVal: string) {}
/ / Vuex data
@State((state: IRootState) = >state . booking. currentStep) step! : number @Getter('person/name') name! : name// Life cyclePrivate created () :void{},// method
public getName(): string {
let storeName = name
return storeName
}
}
</script>
Copy the code
§ How to write a vue3 + typescript component:
- Vue3 + TypeScript complete project Tutorial
import { defineComponent, PropType } from 'vue'
interface Student {
name: string
class: string
age: number
}
/ / style option
const Component = defineComponent({
props: {
success: { type: String },
callback: {
type: Function as PropType<() = > void>},student: {
type: Object as PropType,
required: true}},data() {
return {
message: 'Vue3 code style'}},computed: {
reversedMessage(): string {
return this.message.split(' ').reverse().join(' ')}}})// Composition API style
const Component = defineComponent(() = > {
const year = ref(2020)
const month = ref('9')
month.value = 9 // OK
const result = year.value.split(' ') // => Property 'split' does not exist on type 'number'
// reactive
const student = reactive({ name: 'o yong'.age: 16})})Copy the code