Front end interview questions

Jacquelyn38 2021-06-18 03:00:17
end interview questions

Basic knowledge points and high frequency test questions

JavaScript Basics

console.log(1 < 2 < 3); console.log(3 > 2 > 1); // Write the code execution results , And explain why // Answer and analysis true false For operators >、<, The general calculation is from left to right First question :1 < 2 be equal to true, then true < 3,true == 1 , So the result is true Second question :3 > 2 be equal to true, then true > 1, true == 1 , So the result is false /*********************************/ [typeof null, null instanceof Object] // Write the result of code execution , And explain why // Answer and analysis ["object", false] 1)typeof The operator returns a string , Represents the type of uncomputed operand type result Undefined "undefined" Null "object" Boolean "boolean" Number "number" String "string" Symbol "symbol" Function object "function" Any other object "object" typeof null === 'object';// From the beginning javascript this is it JavaScript The value in is represented by a label representing the type and the actual data value . The type label of the object is 0. because null Represents a null pointer ( Most platform values are 0x00), therefore ,null The type label of the is also becoming 0,typeof null It's wrong to return "object". This is a bug, But refused to fix , Because of the impact of web Too many systems 2)instanceof Operator is used to test whether an object has a constructor in its prototype chain prototype attribute null Not in Object Prototype creation , Therefore return false /*********************************/ // The loop trap var END = Math.pow(2, 53); var START = END - 100; var count = 0; for (var i = START; i <= END; i++) { count++; } console.log(count); // Write the correct print , And explain why ? // Answer and analysis This will fall into a dead circle ,2^53 It's the maximum value , therefore 2^53+1 be equal to 2^53 /*********************************/ var a = Date(0); var b = new Date(0); var c = new Date(); [a === b, b === c, a === c]; // Write the code execution results // Answer and analysis [false,false,false] It's important to note that you can only call Date Constructor to instantiate the date object : Call it as a regular function ( That is, without new The operator ) Will return a string , Instead of a date object . in addition , Unlike anything else JavaScript type ,Date Object has no literal format . a Is string ,b and c yes Date object , also b It stands for 1970 The initial time of the year , and c It represents the current time . /*********************************/ // Comma expression var x = 20; var temp = { x: 40, foo: function() { var x = 10; console.log(this.x); } }; (,; // Write out the printed results 20 Comma operator , The comma operator calculates its operands from left to right , Returns the value of the last operand . therefore (,; Equivalent to var fun =; fun();,fun Invocation time this Point to window, So back 20. /*********************************/ call chaining // Realization (5).add(3).minus(2) function // console.log((5).add(3).minus(2)); // 6 /* answer :12 arguments in c The value of the or 1 Will not become 10, because a Function with default value , Just press the ES Method analysis of ,ES6 It has block level scope , therefore c The value of will not change */ Number.prototype.add = function (number) { if (typeof number !== 'number') { throw new Error(' Please enter a number ~'); } return this + number; }; Number.prototype.minus = function (number) { if (typeof number !== 'number') { throw new Error(' Please enter a number ~'); } return this - number; }; console.log((5).add(3).minus(2)); /*********************************/ var a = 1; (function a () { a = 2; console.log(a); })(); // answer ƒ a () { a = 2; console.log(a); } /* The function expression that is called immediately (IIFE) There is one I am independent Scope , If the function name conflicts with the internal variable name , Will always execute the function itself ; So the output of the above result is the function itself ; */ /*********************************/ var a = [0]; if(a){ console.log(a == true); }else{ console.log(a); } /* answer :false When a Appear in the if In the condition of , Converted to Boolean , and Boolean([0]) by true, So make the next step a == true, When comparing ,[0] Was converted to 0, therefore 0==true by false js The rule is : If you are comparing the values of the original type , The value of the original type is converted into a numerical value and then compared 1 == true //true 1 === Number(true) 'true' == true //false Number('true')->NaN Number(true)->1 '' == 0//true '1' == true//true Number('1')->1 Object compared to the original type value , Object is converted to the value of the original type and then compared . undefined and null When compared with other types , The result is false, When they compare with each other, it turns out that true. I don't want the one below sadfasdfasdfasdfsadfasdffasdfasdf Some implicit transformations Arrays are never primitive To primitive It will be called implicitly first join become “0”,string and boolean When comparing , Both of them first turn into number Compare the types again , The last is 0==1 Compared with var a = [1]; if(a){ console.log(a == true); }else{ console.log(a); } // true !![] //true The conversion of an empty array to a Boolean is true, !![0]//true Array to Boolean is true [0] == true;//false When comparing arrays with Booleans, it becomes false Number([])//0 Number(false)//0 Number(['1'])//1 So when a Appear in the if In the condition of , Converted to Boolean , and Boolean([0]) by true, So make the next step a == true, When comparing ,js The rule is : If you are comparing the values of the original type , The value of the original type is converted into a numerical value and then compared 1 == true //true 1 === Number(true) 'true' == true //false Number('true')->NaN Number(true)->1 '' == 0//true '1' == true//true Number('1')->1 Object compared to the original type value , Object is converted to the value of the original type and then compared . undefined and null When compared with other types , The result is false, When they compare with each other, it turns out that true. */ /****************************/ const a = [1,2,3], b = [1,2,3], c = [1,2,4], d = "2", e = "11"; console.log([a == b, a === b, a > c, a < c, d > e]); // Write the correct print // answer [false,false,false,true,true] // analysis 1)JavaScript There are two ways to compare : Strict comparison operators and conversion type comparison operators . For strict comparison operators (===) Come on , Only if two operands have the same type and equal values is true, And for the widely used comparison operators (==) Come on , Before we make a comparison , Convert two operands to the same type . For relational operators ( such as <=) Come on , Will first convert the operands to their original values , Make them the same type , And then compare them . When both operands are objects ,JavaScript Will compare their internal references , If and only if their references point to the same object in memory ( Area ) The time is equal , That is, they have the same reference address in stack memory . javascript in Array Also object , So here a,b,c Obviously references are different , So here a==b,a===b All for false. 2) Compare the size of two arrays , That is to compare two objects When two objects are compared , Will be converted to the value of the original type , Then compare . Object to the value of the original type , The algorithm is called first valueOf Method ; If it's still an object , Then call toString Method . ①valueOf() Method returns the original value of the specified object . JavaScript call valueOf Method to convert the object to the original value . You rarely have to call it yourself valueOf Method ; When you encounter an object with the original value you want to expect ,JavaScript It will be called automatically . By default ,valueOf Method by Object After each inherited object . Each built-in core object will override this method to return the appropriate value . If the object has no original value , be valueOf The object itself is returned . ②toString() Method returns a string representing the object . Each object has one toString() Method , When the object is represented as a text value , Or an object is automatically called when it is referenced in the expected string way . By default ,toString() The method is each Object Object inheritance . If this method is not overridden in the custom object ,toString() return "[object type]", among type It's the type of object . ③ after valueOf,toString To deal with , So here a,c It will eventually be converted to "1,2,3" And "1,2,4"; 3) Compare the size of two strings After the array above is converted to a string , Then compare the size . MDN The description in is like this : String comparisons are based on standard dictionaries Unicode Value to compare . Strings are compared in dictionary order .JavaScript Inside the engine, first compare the first character of Unicode Code points . If equal , And then compare the second character Unicode Code points , And so on . So here "1,2,3" < "1,2,4", Output true, Because the character in front of it is unicode Every yard is equal , So finally, the comparison 3 and 4 Of unicode Code points . and 3 Of Unicode Code point is 51,4 Of uniCode Code point is 52, therefore a<c. "2" > "11" It's the same thing , This is also a problem sometimes encountered in development , So we need to pay attention to it when we compare operations . 4) About valueOf,toString Call order of ①javascript The process of object to string conversion in is as follows : If the object has toString() Method ,javaScript This method is called first . If you return an original value ( The original values include null、undefined、 Boolean value 、 character string 、 Numbers ),javaScript Will convert the original value to a string , And returns a string as the result . If the object does not have toString() Method , Or call toString() Method does not return the original value , be javaScript Will judge whether there is valueOf() Method , Call this method if it exists , If you return the original value ,javaScript Converts the original value to a string as the result . If javaScript Unable to call toString() and valueOf() When returning the original value , A type error exception warning will be given . such as :String([1,2,3]); Converts an object to a string var a = [1,2,3]; a.valueOf = function(){ console.log("valueOf"); return this } a.toString = function(){ console.log('toString') return this } String(a); Because what I'm returning here is this, Last , So if javaScript Unable to call toString() and valueOf() When returning the original value , A type error exception warning will be given . ②javaScript The process of converting objects into numbers in : javaScript Priority is given to judging whether the object has valueOf() Method , If yes, call , If you return an original value ,javaScript The original value is converted to a number and as a result . If the object does not have valueOf() Method ,javaScript It will call toString() Methods , If you return the original value ,javaScript The original value is converted to a number and as a result . If javaScript Unable to call toString() and valueOf() When returning the original value , A type error exception warning will be given . such as :Number([1,2,3]); Converts an object to a string /*****************************************/ var a = ?; if(a == 1 && a== 2 && a== 3){ console.log(1); } /* The comparison operation involves many different types of values , There's a lot of implicit conversions involved , There are many rules, even experienced programmers can't remember them all , Especially when it comes to `==` and `!=` When you do the calculation . So some teams have banned `==` Operator substitution `===` Strictly equal . */ // Answer 1 var aᅠ = 1; var a = 2; var ᅠa = 3; if(aᅠ==1 && a== 2 &&ᅠa==3) { console.log("1") } /* Check your fault finding ability , Be careful if The space inside , It's a Unicode Space character , Don't be ECMA The script is interpreted as a space character ( This means that it is a valid character for the identifier ). So it can be interpreted as var a_ = 1; var a = 2; var _a = 3; if(a_==1 && a== 2 &&_a==3) { console.log("1") } */ // Answer two var a = { i: 1, toString: function () { return a.i++; } } if(a == 1 && a == 2 && a == 3) { console.log('1'); } /* If the value of the original type is compared with the object , Object will be converted to the value of the original type , Then compare . Object to the value of the original type , The algorithm is called first valueOf Method ; If it's still an object , Then call toString Method . */ // Answer three var a = [1,2,3]; a.join = a.shift; console.log(a == 1 && a == 2 && a == 3); /* A more ingenious way ,array It also belongs to the object , For array objects ,toString Method returns a string , The string is composed of the values of each element in the array toString() The return value is called join() Methods the connection ( Separated by commas ) form . Array toString Will call its own join Method , Here you put your own join The method should be written as shift, Return the first element at a time , And the original array removes the first value , It just makes the judgment right */ // Answer 4 var i = 0; with({ get a() { return ++i; } }) { if (a == 1 && a == 2 && a == 3) console.log("1"); } /* with It is also the object that is seriously recommended not to be used , Here we also use its features to use objects in code blocks get Method dynamically returns i. */ // Answer five var val = 0; Object.defineProperty(window, 'a', { get: function() { return ++val; } }); if (a == 1 && a == 2 && a == 3) { console.log('1'); } /* Global variables are also equivalent to window An attribute on an object , Here we use defineProperty Defined a Of get It also makes the dynamic return value . and with There are some similarities . */ // Answer six let a = {[Symbol.toPrimitive]: ((i) => () => ++i) (0)}; if (a == 1 && a == 2 && a == 3) { console.log('1'); } /* ES6 A new type of raw data is introduced Symbol, Represents a unique value . We used to use... When defining the internal private properties of a class __xxx , This naming method avoids others from defining the same attribute name to cover the original attribute , With Symbol After that, we can use Symbol Instead of this method , And there's no need to worry about being covered . In addition to defining what you use Symbol Out of value ,ES6 It also provides 11 Built in Symbol value , Point to methods used within a language .Symbol.toPrimitive It's one of them , It points to a method , Indicates that the object is converted to a value of the original type , Will call this method , Returns the original type value of the object . Here is to change this property , Change its value to a Closure Return function . */ This kind of code is not usually written in business , The key point is the investigation of knowledge points /*******************************************/ let a = {n: 1}; let b = a; a.x = a = {n: 2}; console.log(a.x) console.log(b.x) answer : undefined {n:2} Be careful : 1: The priority of a point is greater than that of an equal sign 2: Objects are stored as pointers , Each new object is a new storage address analysis : - `var b = a;` b and a All point to the same address . - `.` Has a higher priority than `=`. So first execute `a.x`, So now `a` and `b` All are `{n: 1, x: undefined}`. - `=` It's right to left . So it's execution `a = {n: 2}`, therefore `a` Yes `{n: 2}` - Re execution `a.x = a`. Note here ,`a.x` It's the first thing to do , It's already `{n: 1, x: undefined}` This is the address , Instead of the one that's on `a`, So it's not `{n: 2}` 了 . and `b` And the old `a` It's pointing to an address , therefore `b` Has also changed . - however ,`=` On the right a, It's a new... That has pointed to a new address `a`. - therefore ,`a.x = a` It can be seen as `{n: 1, x: undefined}.x = {n: 2}` - Finally it is concluded that a = { n: 2 }, b = { n: 1, x: { n: 2 } } /*****************************************/ // Implement a template engine let template = ' I am a {{name}}, Age {{age}}, Gender {{sex}}'; let data = { name: ' full name ', age: 18 } render(template, data); // I'm name , Age 18, Gender undefined function render(template,data){ // your code } // Supplementary code , Make code execute correctly // Code implementation function render(template, data) { const reg = /\{\{(\w+)\}\}/; // Template string regular if (reg.test(template)) { // Determine whether there is a template string in the template const name = reg.exec(template)[1]; // Find the field of the first template string in the current template template = template.replace(reg, data[name]); // Render the first template string return render(template, data); // Recursively render and return the rendered structure } return template; // If the template does not have a template string to return directly } /*****************************************/ What is the packaging object (wrapper object)? // answer 1) Review the JS Data type of ,JS Data types are divided into two categories , Basic types and reference types ① Basic types :Undefined,Null,Boolean,Number,String,Symbol,BigInt ② Reference type :Object,Array,Date,RegExp etc. , It's the object . 2) The reference types include methods and properties , But there is no basic type , But we often see the following code let name = "marko"; console.log(typeof name); // "string" console.log(name.toUpperCase()); // "MARKO" name The type is string, Basic type , So it has no properties or methods , But in this case , We called a toUpperCase() Method , It doesn't throw errors , It also returns the variable value of the object . The reason is that the value of the base type is temporarily converted or cast to an object , therefore name Variables behave like objects . except null and undefined Each basic type has its own wrapper object . That is to say :String,Number,Boolean,Symbol and BigInt. under these circumstances ,name.toUpperCase() Behind the scenes, it looks like this : console.log(new String(name).toUpperCase()); // "MARKO" After accessing properties or calling methods , The newly created object will be discarded immediately . 

Shake proof / throttle

const debounce = (fn,delay) => { // Introduce the principle of anti shake function , And implement // your code } const throttle = (fn,delay = 500) => { // Introduce the principle of throttling function , And implement // your code } // Answer and analysis /* 1) Anti shake function principle : When the event is triggered n Seconds before the callback , If in this n It's triggered in seconds , Then the time will be counted again . Applicable scenario : ① Button submit scenario : Prevent multiple submissions button , Perform only the last commit ② Server verification scenario : Form validation needs server cooperation , Only the last time a continuous input event is executed , And search association words have similar functions */ // The simplified version of handwriting realizes const debounce = (fn,delay) => { let timer = null; return (...args) => { clearTimeout(timer); timer = setTimeout(() => { fn.apply(this.args); },delay) } } /* 2) Principle of throttling function : Within one unit time , Function can only be triggered once . If multiple functions are triggered in this unit time , Only once . Anti shake is to delay execution , And throttling is interval execution , Function throttling is executed every other period of time Applicable scenario : ① Drag scene : Only once in a fixed time , Prevent UHF trigger position change ② Zoom scene : Monitor browser resize ③ Animated scene : Avoid triggering animation multiple times in a short time to cause performance problems */ // The simplified version of handwriting realizes // ① Timer implementation const throttle = (fn,delay = 500) =>{ let flag = true; return (...args) => { if(!flag) return; flag = false; setTimeout(() => { fn.apply(this,args); flag = true; },delay); }; } // ② Timestamp implementation const throttle = (fn,delay = 500) => { let preTime =; return (...args) => { const nowTime =; if(nowTime - preTime >= delay){ preTime =; fn.apply(this,args); } } } 

new Implementation principle of , Simulate it

// First ,new What does the operator do new Operator to create an instance of a user-defined object type or a built-in object with a constructor .new The keyword will do the following Create an empty simple JavaScript object ( namely {}); Link the object ( That is, set the constructor of the object ) To another object ; Will step 1 The newly created object serves as this The context of ; If the function does not return an object , Then return to this. That is, the new object created , otherwise , Returns the object returned in the constructor . // Refer to the answer :1. Simple implementation function newOperator(ctor) { if (typeof ctor !== 'function'){ throw 'newOperator function the first param must be a function'; } // ES5 arguments Turn it into an array You can also use it ES6 [...arguments], Aarry.from(arguments); var args =, 1); // 1. Create an empty simple JavaScript object ( namely {}) var obj = {}; // 2. Link to the newly created object ( That is to set the __proto__) To the prototype object of the function prototype On obj.__proto__ = ctor.prototype; // 3. Will step 1 The newly created object serves as this The context of var result = ctor.apply(obj, args); // 4. If the function does not return an object , The newly created object is returned var isObject = typeof result === 'object' && result !== null; var isFunction = typeof result === 'function'; return isObject || isFunction ? result : obj; } // test function company(name, address) { = name; this.address = address; } var company1 = newOperator(company, 'yideng', 'beijing'); console.log('company1: ', company1); // Refer to the answer :2. A more complete implementation /** * Simulation Implementation new The operator * @param {Function} ctor [ Constructors ] * @return {Object|Function|Regex|Date|Error} [ Return results ] */ function newOperator(ctor){ if(typeof ctor !== 'function'){ throw 'newOperator function the first param must be a function'; } // ES6 Is pointing to the constructor = ctor; // 1. Create a new object , // 2. And perform [[Prototype]] link // 4. adopt `new` Each object created will eventually be `[[Prototype]]` Linked to this function `prototype` On the object . var newObj = Object.create(ctor.prototype); // ES5 arguments Turn it into an array You can also use it ES6 [...arguments], Aarry.from(arguments); // remove ctor The rest of the arguments to the constructor var argsArr = [], 1); // 3. The generated new object is bound to the function call `this`. // Get ctor Function returns the result var ctorReturnResult = ctor.apply(newObj, argsArr); // Summary 4 The only way to combine these types is Object and Function Two types of typeof null It's also 'object' So it's not equal to null, exclude null var isObject = typeof ctorReturnResult === 'object' && ctorReturnResult !== null; var isFunction = typeof ctorReturnResult === 'function'; if(isObject || isFunction){ return ctorReturnResult; } // 5. If the function does not return an object type `Object`( contain `Functoin`, `Array`, `Date`, `RegExg`, `Error`), that `new` The function call in the expression automatically returns the new object . return newObj; } 

this Point to

// An interview question var a=10; var foo={ a:20, bar:function(){ var a=30; return this.a; } } console.log(; console.log((; console.log((; console.log((,; // answer : 20 20 10 10 // First question /* foo call ,this Point to foo , At this time this refer to foo, Output 20 */ // Second questions ( /* Bracket the expression , The function of brackets is to change the operation order of expressions , And it doesn't matter if you add parentheses here ; amount to, Output 20 */ // Third questions ( /* The equal sign operation , It's like giving it back Definition , namely = function () { var a = 10; return this.a; } It's a normal copy , An anonymous function is assigned to a global variable So at this point Is in window In scope instead of foo = {} This block level scope , So here this It means window, Output 10 */ // Fourth question (, /* 1. The comma operator , 2. Comma expression , The solution process is : So let's evaluate the expression 1 Value , And then calculate the expression 2 Value ,…… All the way up to the expression n Value . Finally, the value of the entire comma expression is the expression n Value . The return value of the comma operator is the value of the last expression . 3. In fact, this is mainly after the comma operator , It's a pure function , Not a reference to an object method , So here this Pointing to window, Output 10 4. Third questions , Fourth question , One is the equal sign operation , One is the comma operation , It's understandable , After assignment , After operator operation , It's all pure functions , Not a reference to an object method . So the function points to this All are windows Of . */ 

If you use one sentence to explain this The direction of , So that is : Who calls it ,this Just point to who . But only through this sentence , Most of the time, we can't accurately judge this The direction of . So we need some rules to help ourselves :

So let's look at this first this Binding rules , Let's take a closer look at , I'll meet you again this The problem of , Can take it easy

  • The default binding
  • // The default binding , Default rules used when no other binding rules can be applied , It's usually an independent function call . function sayHi(){ console.log('Hello,',; } var name = 'yideng'; sayHi(); // Calling Hi() when , Default binding applied ,this Point to global object ( Non strict mode ), In strict mode ,this Point to undefined,undefined Not on this object , Will throw an error . // If running in a browser environment , So the result is Hello,yideng // If in node Running in the environment , The result is Hello,undefined. This is because node in name It's not on a global object . 
  • Implicit binding
  • // Function calls are triggered on an object , That is, there is a context object at the call location . The typical form is function sayHi(){ console.log('Hello,',; } var person = { name: 'yidneg1', sayHi: sayHi } var name = 'yidneg2'; person.sayHi(); // Hello yideng1 // sayHi Function declaration is external , Strictly speaking, it does not belong to person, But in calling sayHi when , Call location will use person The context to reference the function , Implicit binding will call the this( This is the case sayHi Function this) Bind to this context object ( In this case person) 
  • It should be noted that : Only the last layer in the object property chain affects the call location .

  • function sayHi(){ console.log('Hello,',; } var person2 = { name: 'yideng1', sayHi: sayHi } var person1 = { name: 'yideng2', friend: person2 } person1.friend.sayHi(); // Hello yideng1 // Because only the last layer will determine this What is the point , No matter how many layers , In judging this When , We only focus on the last layer , That is to say friend. 
  • ** Implicit binding has a big pitfall ,** Binding is easy to lose ( Or it is easy to mislead us , We think that this What is the point , But it's not ).

  • function sayHi(){ console.log('Hello,',; } var person = { name: 'yideng1', sayHi: sayHi } var name = 'yideng2'; var Hi = person.sayHi; Hi(); // Htllo yideng2 // Hi It points directly to sayHi References to , At call time , Follow person It's nothing to do with half a cent , In response to such problems , I suggest you just keep this format in mind :XXX.fn();fn() If there is nothing before , So it's definitely not implicit binding . 
  • In addition to the above loss , The loss of implicit binding occurs in the callback function ( Event callback is one of them ),

  • function sayHi(){ console.log('Hello,',; } var person1 = { name: 'yideng1', sayHi: function(){ setTimeout(function(){ console.log('Hello,',; }) } } var person2 = { name: 'yideng2', sayHi: sayHi } var name='yideng3'; person1.sayHi(); setTimeout(person2.sayHi,100); setTimeout(function(){ person2.sayHi(); },200); // Hello yideng3 // Hello yideng3 // Hello yideng2 1. The first output is easy to understand ,setTimeout In the callback function of ,this The default binding is used , Non strict mode , It's the global object that executes 2. The second output is not a bit confusing ? Say yes When ,fun Medium this Pointing to XXX Well , Why not this time !Why? In fact, here we can understand : setTimeout(fn,delay){ fn(); }, Quite so person2.sayHi Assigned to a variable , Finally, the variable , This is the time ,sayHi Medium this Obviously and person2 It doesn't matter . 3. The third, though, is setTimeout In the callback , But we can see , This is the implementation of person2.sayHi() Using implicit binding , So this is this Pointing to person2, Has nothing to do with the current scope . 
  • See if I'm a little tired here

  • According to the binding
  • Explicit binding is easier to understand , It is through call,apply,bind The way , Explicitly specify this The object that is pointed to .

  • call,apply and bind The first parameter of , Is the corresponding function this The object that is pointed to .call and apply It does the same thing , It's just that there are different ways to pass parameters .call and apply Will execute the corresponding function , and bind No way .

  • function sayHi(){ console.log('Hello,',; } var person = { name: 'yideng1', sayHi: sayHi } var name = 'yideng2'; var Hi = person.sayHi;; //Hi.apply(person) // Hello yideng1 Because using hard binding makes it clear that this Bound to person On . 
  • Hard binding is used , Does it mean that there will be no binding loss encountered by implicit binding ? Obviously not , Don't believe it , Keep looking down .

  • function sayHi(){ console.log('Hello,',; } var person = { name: 'yideng1', sayHi: sayHi } var name = 'yideng2'; var Hi = function(fn) { fn(); }, person.sayHi); // Hello yideng2 The output is zero Hello, Wiliam. The reason is simple ,, person.sayHi) It's going to be this Bound to the Hi Medium this 了 . But in execution fn When , It's equivalent to calling sayHi Method ( remember : person.sayHi Has been assigned to fn 了 , Implicit binding is also missing ), Is not specified this Value , Corresponding to the default binding . Now? , We hope that the binding will not be lost , What to do ? It's simple , call fn When , Also hard bind it . var Hi = function(fn) {; } That's it because person Bound to Hi Function this On ,fn Bind this object to sayHi Function of . At this time ,sayHi Medium this It points to person object . 
  • new binding
  • Create an empty object , In the constructor this Point to this empty object

  • This new object is executed [[ Prototype ]] Connect

  • Execute the constructor method , Properties and methods are added to this In the referenced object

  • If no other object is returned in the constructor , Then the return this, That is, the new object created , otherwise , Returns the object returned in the constructor .

  • javaScript and C++ Dissimilarity , There is no class , stay javaScript in , Constructors just use new The function called when the operator , These functions are no different from ordinary functions , It doesn't belong to a certain class , It's impossible to instantiate a class . Any function can use new To call , So there's no constructor , And only for functions “ To construct call ”

  • We mentioned above new What do operators do

  • therefore , We use new To call a function , Will bind the new object to this function this On .

  • function sayHi(name){ = name; } var Hi = new sayHi('yideng'); console.log('Hello,',; // Hello yideng 
  • Binding priority
  • new binding > Explicitly bound > Implicit binding > The default binding

  • Interested can write a demo Test it

  • We know this There are four binding rules , But if multiple rules are applied at the same time , What do I do ?

  • obviously , We need to know which binding method has higher priority , The priority of these four bindings is :

  • Binding exception
  • There are exceptions to everything ,this The same is true of the rule of .

  • If we were to null Or is it undefined As this The binding object passed in call、apply Or is it bind, These values are ignored when called , The actual application is the default binding rules .

  • var foo = { name: 'yideng1' } var name = 'yideng2'; function bar() { console.log(; }; //yideng2 Because the default binding rule is applied in practice . 
  • Arrow function
  • In function body this object , Inherited is the outer code block this.

  • Can't be used as a constructor , in other words , Not available new command , Otherwise, an error will be thrown .

  • Not available arguments object , The object does not exist inside the function . If you want to use , It can be used rest Parameters instead of .

  • Not available yield command , So the arrow function cannot be used as Generator function .

  • Arrow function does not have its own this, So it can't be used call()、apply()、bind() These ways to change this The direction of .

  • The arrow function is ES6 In the new , It's different from ordinary functions , Arrow function does not have its own this, its this Inherited from the outer code base this. Arrow function in use , The following points need to be noted :

A comprehensive interview question

function Foo() { getName = function () { console.log(1); }; return this; } Foo.getName = function () { console.log(2);}; Foo.prototype.getName = function () { console.log(3);}; var getName = function () { console.log (4);}; function getName() { console.log (5);} // Please write the following output : Foo.getName(); getName(); Foo().getName(); getName(); new Foo.getName(); new Foo().getName(); new new Foo().getName(); // 2 4 1 1 2 3 3 

The classic point of this question is that it comprehensively examines the JavaScript Comprehensive ability , Includes variable definition Promotion 、this Pointer to 、 Operator priority 、 Prototype 、 Inherit 、 Global variable pollution 、 Knowledge of object property and prototype property priority

Let's see what we did in the first half of the question ,

  • First of all, it defines a name Foo Function of ,

  • For after Foo Created a name getName The static properties of the store an anonymous function ,

  • For after Foo A new prototype object called getName Is an anonymous function of .

  • After that, we create a function variable expression getName Function of ,

  • Finally, I want to make a statement called getName function .

First question :Foo.getName

Nature is to visit Foo Static properties stored on functions , The answer, of course, is 2, Generally speaking, the first question is a little understanding of JS Basic students should be no problem

// Review the basics function User(name) { var name = name; // Private property = name; // Public attribute function getName() { // Private method return name; } } User.prototype.getName = function() { // Public methods return; } = 'yideng'; // Static attribute User.getName = function() { // Static methods return; } var yideng = new User('yideng'); // Instantiation 

A few notes :

  • Call public method , Public attribute , We must instantiate the object first , Also is to use new Operators materialize objects , You can use constructors to instantiate methods and properties of objects , And public methods cannot call private and static methods

  • Static methods and static properties are things that we can call without instantiation

  • And private methods and properties of objects , The outside is not accessible

Second questions :getName();

Call directly getName function . Since it is a direct call, it is called to access the scope in the current scope getName Function of , So we should focus on 4 and 5 On , Follow 1 2 3 It doesn't matter .

So here's the output 4 still 5 Well ?----------- Interaction

There are two pits here

  • One is variable declaration promotion
  • JavaScript There is a mechanism in the interpreter where variable declarations are promoted , That is to say, the function declaration will be promoted to the front of the scope , Even if the code is written at the back , It will still be promoted to the top .
  • The second is the difference between function expression and function declaration
  • Function declaration in JS Function promotion during parsing , So in the same scope , No matter where the function declaration is defined , This function can be called . And the value of the function expression is in JS The runtime determines , And after the expression assignment is complete , This function can call .
  • // An intuitive example getName();// Function declaration var getName = function(){ console.log(' Function expression ') } getName();// Function expression function getName(){ console.log(' Function declaration '); } getName(); // Function expression 
  • So the answer to the second question is 4,5 The function declaration of is 4 The function expression of covers

Third questions :Foo().getName()

First executed. Foo function , And then call Foo Function's return value object's getName Property function

Foo The first sentence of the function getName = function () { console.log(1); }; It's a function assignment statement , Notice that it doesn't var Statement ,

So start with the present Foo Find... In the scope of the function getName Variable , No, . To the upper level of the current function scope , That is, to find out whether there is getName Variable , eureka , In the second question console.log(4) function , Assign the value of this variable to function(){console.log(1)}.

This is actually going to be in the outer scope of getName The function has been modified .

Be careful : If you still can't find it here, you will always find it up window object , if window There is no such thing as getName attribute , It's just window Object getName Variable .

after Foo The return value of the function is this,this The direction of is determined by the way the function is called . And the direct call method here ,this Point to window object .

therefore Foo Function returns window object , Equivalent to execution window.getName(), and window Medium getName Has been modified to alert(1), So eventually it will output 1

Two knowledge points are examined here , One is the variable scope problem , One is this Point to the problem

About this,this The direction of is not certain when the function is defined , It can only be determined when the function is executing this Who is it pointing to , actually this Finally, it points to the object that calls it

So the third question is actually window Calling **Foo()** function , therefore this The direction is window

Fourth question :getName()

Call directly getName function , amount to window.getName(), Because this variable has been Foo Function execution time changed , So the result is the same as the third question , by 1, in other words Foo After the implementation of the overall getName The function has been rewritten once , So the result is Foo() The one who performs the rewrite getName function

The fifth question is :new Foo.getName()

What we are looking at here is JS Operator priority problem of

MDN Operator priority :\_Precedence

First of all, let's look at the priority 18 And the 17 All about new The priority of the ,new ( With parameter list ) Than new ( No parameter list ) Higher than function call , Visit peers with members

new Foo.getName(); This is the priority of Equivalent to : new (Foo.getName)(); // Point priority (18) Than new No parameter list (17) High priority // When the point operation is finished, there is a bracket (), This is the time to become new With parameter list (18), So direct execution new, Of course, some friends may have questions about why they meet () No function calls new Well , That's because of function calls (17) Than new With parameter list (18) Low priority . Member visit (18)->new With parameter list (18) So this is actually going to be getName Function as a constructor to execute , Then pop up 2. 

Sixth question :(new Foo()).getName()

The only difference between this question and the previous one is that Foo There is an extra bracket , We can see that there is a difference in priority between the bracketed and the unsettled when we ask the fifth question

1. The difference from the fourth question is that there are brackets and no brackets , Here in parentheses is new With parameter list ,new The priority with a parameter list is 18, The priority of points is also 18, The priority is the same, from left to right . 2. So here is a list of parameters to be executed first , The priority of the execution point , Finally, the function calls 3. There is a point of knowledge here ,fn There are return values as constructors , stay JS Constructor can have return value or not a. no return value , Returns the instantiated object b. There is a return value , Check whether the return value is of reference type . Non reference type , Such as basic type (String,Number,Boolean,Null,Undefined) Same as no return value , Actually returns the instantiated object . Reference type , The actual return value is this reference type 4. here fn Function returns this,this In the constructor, it represents the currently instantiated object , Final fn Function returns the instantiated object . The final call , Instantiate the object's getValue function , Because in Foo The constructor does not add any properties to the instantiated object , The prototype object of the current object (prototype) Search for getName function . So the output 3.

Seventh question :new new Foo().getName();

And then there's the priority issue , The answer doesn't really matter here , The key is whether you really know what the interviewer is looking at us .

 In the end is new ((new Foo()).getName)(); new With parameter list (18)->new With parameter list (18) Initialize first Foo Instantiate the object , And then put the getName Function as constructor again new, So the end result is 3 


function yideng(){} const a = {}, b = Object.prototype; console.log(a.prototype === b); console.log(Object.getPrototypeOf(a) === b); console.log(yideng.prototype === Object.getPrototypeOf(yideng)); // Write out the execution results , And explain why ? // answer false true false // analysis : 1)a.prototype === b =>false prototype Properties are properties that are unique to functions , When you create a function ,js Will automatically add... To this function prototype attribute , Value is an empty object . The instance object has no prototype Attribute . therefore a.prototype yes undefined, The first result is false. 2)Object.getPrototypeOf(a) === b =>true First of all, we need to make clear the relationship between the object and the constructor , When the object is created , Its __proto__ Will point to its constructor prototype attribute Object It's actually a constructor (typeof Object As the result of the "function"), Use literal quantities to create objects and new Object Creating objects is the same , therefore a.__proto__ That is to say Object.prototype, therefore Object.getPrototypeOf(a) And a.__proto__ It's the same , The second result is true 3)yideng.prototype === Object.getPrototypeOf(yideng) =>false Key points :f.prototype and Object.getPrototypeOf(f) It's not the same thing ①f.prototype It's using new Created f The prototype of the instance : f.prototype === Object.getPrototypeOf(new f()); // true ②Object.getPrototypeOf(f) yes f Prototypes of functions : Object.getPrototypeOf(f) === Function.prototype; //true So the answer is false // Knowledge point __proto__( Implicit prototype ) And prototype( Explicit prototypes ) 1) What is it? ? ① Explicit prototypes explicit prototype property: After each function is created, it will have a name called prototype Properties of , This property points to the prototype object of the function .( It should be noted that , adopt Function.prototype.bind The function constructed by method is an exception , It has no prototype attribute ) ② Implicit prototype implicit prototype link: JavaScript Any object in has a built-in property [[prototype]], stay ES5 There was no standard way to access this built-in property before , But most browsers support using __proto__ To visit .ES5 For this built-in property standard Get Method Object.getPrototypeOf().( Be careful :Object.prototype This object is an exception , its __proto__ The value is null) ③ The relationship between the two : The implicit prototype points to the function that created the object (constructor) Of prototype 2) What is the role ? ① The role of explicit prototypes : It is used to implement prototype based inheritance and property sharing . ② The role of implicit prototypes : Form a prototype chain , Also used to implement prototype based inheritance . for instance , When we visit obj In this object x Attribute , If in obj I can't find it in China. , Then it will follow __proto__ Search for . 3)__proto__ The direction of : __proto__ How to judge the direction of the ? according to ECMA Definition 'to the value of its constructor’s "prototype" ' ---- Point to the explicit prototype of the function that created the object . So the key is to find the constructor that creates this object , Let's take a look JS How objects are created in , At first glance, there seem to be three ways :(1) The way in which objects are literally measured (2)new The way (3)ES5 Medium Object.create(). But there is essentially only one way , That is, through new To create . Why do you say that , First of all, the literal way is a syntax sugar for developers to create objects more conveniently , Nature is var o = new Object(); o.xx = xx;o.yy=yy;

Loading pages and rendering passes

When answering questions , The key is to grasp the core point , Make the point comprehensive , And then add a little more parsing , Be concise and to the point , have a lucid brain , Don't procrastinate .

Interview questions : The browser's process from loading to rendering the page

  • First answer the loading process , Answer the main point
  • Browser according to DNS The server gets the domain name IP Address

  • To this IP Sent by the machine HTTP request

  • Server received 、 Process and return HTTP request

  • The browser gets the returned content

  • A little analysis
  • For example, enter... In the browser https// When , First pass through DNS analysis , Corresponding IP yes, Then the browser sends the IP send out HTTP request .

  • server Termination received HTTP request , And then it's calculated ( Push different content to different users ), return HTTP request , The returned content is actually a pile of HMTL Format string , Because only HTML Format browser can correctly parse , This is a W3C Standard requirements .

  • Next is the rendering process , Answer the main point
  • according to HTML Structure generation DOM Trees

  • according to CSS Generate CSSOM

  • take DOM and CSSOM Integrate to form RenderTree

  • according to RenderTree Start rendering and showing

  • encounter <script> when , Will perform and block rendering

  • To analyze
  • The browser has got server End return HTML Content , Start parsing and rendering . The first thing I got was a bunch of strings , It must first be structured into the basic data structure that the computer is good at processing , So we should put HTML String to DOM Trees —— Tree is one of the most basic data structures .

  • During parsing , If you encounter <link href="..."> and <script src="..."> This kind of external chain loading CSS and JS The label of , The browser will download it asynchronously , Download process and download above HTML The process is the same . It's just , The string downloaded here is CSS perhaps JS Format .

  • The browser will CSS Generate CSSOM, then DOM and CSSOM Integrated into RenderTree , And then for RenderTree You can render . You can think about it , Yes DOM structure 、 There are styles , At this point, the conditions for rendering can be met . in addition , There's a problem that can also be explained here —— Why should we CSS Put it in HTML Head ?—— This will let the browser get it as soon as possible CSS Generate as early as possible CSSOM, And then in the parsing HTML After that, the final RenderTree, Render once . If CSS Put it in HTML Bottom , There will be render jams , Impact performance and experience .

  • Last , During rendering , If you encounter <script> Stop rendering , perform JS Code . Because browser rendering and JS Execution shares a thread , And it has to be single threaded , Multithreading produces rendering DOM Conflict . stay <script> After the content is executed , The browser continues rendering . Finally, let's think about one more question —— Why should we JS Put it in HTML Bottom ?—— JS Placing it at the bottom ensures that the browser will render the existing HTML Content , Let users see the content first , Have a good experience . in addition ,JS If execution involves DOM operation , Have to wait DOM The analysis is complete ,JS At the bottom of the execution ,HTML It must have all been interpreted as DOM structure .JS If you put it in HTML Top ,JS When it comes to execution HTML I haven't had time to convert to DOM structure , There may be a mistake .

performance optimization

Performance optimization is also a common test in interviews , This kind of topic has great expansibility , It can be expanded into a lot of small details , And it's a big challenge to one's technical vision and business ability .

  • The optimization principle is based on a better user experience , Goal is to
  • Use more memory 、 Caching or other methods

  • Reduce CPU and GPU Calculation , Show it faster

  • To optimize the direction
  • CSS Put it in the front ,JS Put it back

  • Lazy loading ( Picture lazy loading 、 Pull down to load more )

  • Reduce DOM Inquire about , Yes DOM Query as cache

  • Reduce DOM operation , Try to combine multiple operations to perform (DocumentFragment

  • Event throttling

  • Do it early (DOMContentLoaded

  • Use SSR Render Back-End , The data is output directly to HTML in , Reduce browser usage JS Template render page HTML Time for

  • window.addEventListener('load', function () { // All resources of the page are loaded before execution , Including pictures 、 Video etc. }) document.addEventListener('DOMContentLoaded', function () { // DOM After rendering, it can be executed , Now the picture 、 The video may not be loaded yet }) 
  • Compression and merging of static resources (JS Code compression merge 、CSS Code compression merge 、 Sprite )

  • Static resource cache ( Resource name plus MD5 stamp )

  • Use CDN Make resources load faster

  • Reduce page size , Improve network load

  • Optimize page rendering



Interview questions : What is? xss attack

XSS The full name is Cross Site Scripting( namely Cross site scripts ), In order to and CSS distinguish , So it's called XSS.XSS An attack is the execution of a malicious script in a browser ( Whether it's cross domain or co domain ), So as to get the user's information and operate .

These operations can generally accomplish the following things :

  1. steal Cookie.

  2. Monitor user behavior , For example, input the account password and send it directly to the hacker server .

  3. modify DOM Fake login forms .

  4. Create a floating window ad on the page .

General situation ,XSS There are three ways to attack —— Storage type reflective and Document type . The principles are relatively simple , Let's get to know

  • Storage type

Storage type , As the name implies, it stores malicious scripts , exactly , Storage type XSS The script is stored in the database of the server , Then execute these scripts on the client side , So as to achieve the effect of attack .

A common scenario is to submit a script code in the comment area , If the front and back ends don't do a good job of escaping , The comments are stored in the database , During page rendering Direct execution , It's equivalent to executing an unknown logic JS Code , It's very scary . This is the storage type XSS attack .

  • reflective

reflective XSS Refers to malicious script as Part of the network request .

So let's say I type in :<script>alert(" You're done. ")</script> 

This poplar , On the server side, you will get q Parameters , Then return the content to the browser , The browser uses this content as HTML Part of the analysis , Discovery is a script , Direct execution , So it's attacked .

It's called reflective , Because the malicious script is passed as a parameter of the network request , Through the server , And then reflect back to HTML In the document , Execution Analysis . and Storage type The difference is , The server does not store these malicious scripts .

  • Document type

Document type XSS The attack doesn't go through the server , It's the role of an intermediary , Hijack to network packet during data transmission , then Modify the html file

Such hijackings include WIFI Router hijacking perhaps Local malware etc. .

Preventive measures

I understand three kinds of XSS Principle attacks , We can find one thing in common : It's all about allowing malicious scripts to execute directly in the browser .

Then guard against it , It is to avoid the execution of these script code .

To accomplish this , Must do

Never trust any user's input !

Both in the front end and the server end , It's all about user input transcoding perhaps Filter .

Such as :

<script>alert(' You're done. ')</script> 

After transcoding, it becomes :

&lt;script&gt;alert(&#39; You're done. &#39;)&lt;/script&gt; 

Such code is in html Parsing cannot be performed .

Of course, you can also use keyword filtering , take script Tag to delete . So now the content is just :

utilize HttpOnly

quite a lot XSS Attack scripts are used to steal Cookie, And set up Cookie Of HttpOnly After attribute ,JavaScript Can't read Cookie Value . This can also be a good defense XSS attack .


Interview questions : The way CSRF attack

What is? CSRF attack ?

CSRF(Cross-site request forgery), I.e., cross-site request forgery , It means that hackers induce users to click on links , Open the hacker's website , Then hackers use users Current login status Initiate cross station request .

for instance , You click on the hacker's carefully selected picture of little sister in a forum , When you click , Entered a new page .

So congratulations , Being attacked :)

You may be curious , Why was it suddenly attacked ? Next we'll break it down when you click on the link , What did hackers do behind the scenes .

There are three things that can be done . List the following :

1. Send automatically GET request

There may be a code like this in the hacker's web page :

<img src=""> 

Automatically send... After entering the page get request , It is worth noting that , This request will automatically bring with it information about Of cookie Information ( Here is the assumption that you are already in Has logged in to ).

If there is no corresponding authentication mechanism on the server side , It may think that the request is made by a normal user , Because of the corresponding cookie, Then carry out the corresponding operations , It can be transfer remittance and other malicious operations .

2. Send automatically POST request

The hacker may have filled out a form by himself , Wrote a script for auto submission .

<form id='hacker-form' action="" method="POST"> <input type="hidden" name="user" value="hhh" /> <input type="hidden" name="count" value="100" /> </form> <script>document.getElementById('hacker-form').submit();</script> 

It will also carry the corresponding users cookie Information , Let the server mistakenly think that a normal user is operating , Make all kinds of malicious operations possible .

3. Induced Click to send GET request

On the hacker's website , Maybe put a link , Drive you to click :

<a href="https://xxx/info?user=hhh&count=100" taget="_blank"> Click to enter the world of immortality </a> 

After clicking , Send automatically get request , Next and Send automatically GET request Part of the same .

This is it. CSRF Principle attacks . and XSS Attack contrast ,CSRF The attack does not need to inject malicious code into the user's current page html In the document , But jump to a new page , Using the server Validation vulnerabilities and User's previous login status To simulate the operation of users .

Preventive measures

CSRF attack One of the important links in is to automatically send the Cookie, And then this one Cookie Simulate the identity of the user . So in Cookie Above and below is the best choice for prevention .

just , stay Cookie There is a key field , Can be on request Cookie Some restrictions on carrying , This field is SameSite.

SameSite It can be set to three values ,StrictLax and None.

a. stay Strict In mode , The browser completely forbids the third party to request to carry Cookie. For example, request The website can only be in Domain name can only be carried by request Cookie, No requests on other sites .

b. stay Lax Pattern , Just a little more relaxed , But only in get Method submit form Or a Tag send get request You can carry Cookie, In no other case can .

c. stay None In mode , That's the default mode , The request will be carried on automatically Cookie.

2. Verify source site

This requires two fields in the request header : Origin and Referer.

among ,Origin Only domain name information , and Referer Contains Specifically Of URL route .

Of course , Both of them can be forged , adopt Ajax The user-defined request header in , A little less secure .

3. CSRF Token

How does it work ?

First , When the browser sends a request to the server , The server generates a string , Plant it on the returned page .

Then if the browser wants to send a request , You have to bring this string , Then the server verifies that it's legal , If it is illegal, it will not respond . This string means CSRF Token, Usually third party sites can 't get this token, So it is rejected by the server .

Preventive measures : utilize Cookie Of SameSite attribute Verify source site and CSRF Token.

Algorithm problem

/* Given one only includes '(',')','{','}','[',']' String , Determines whether the string is valid Valid string must be full ⾜: 1. The left bracket must be ⽤ Right parentheses of the same type close . 2. The left parenthesis must be closed in the correct order . Note that an empty string can be considered a valid string . Example 1: transport ⼊: "()" Output : true Example 2: transport ⼊: "()[]{}" Output : true Example 3: transport ⼊: "(]" Output : false Example 4: transport ⼊: "([)]" Output : false Example 5: transport ⼊: "{[]}" Output : true */ // Ideas Out of the stack 、 The idea of entering the stack 1) First , From the example above, we can analyze what kind of bracket matching is complex condition , Two cases . ① The first one is ( Non nested case ):{} [] ; ② The second kind ( Nesting ):{ [ ( ) ] } . Except in both cases, it is not eligible . 2) then , Let's see these brackets from right to left as stack structures , On the right is the top of the stack , On the left is the end of the stack . 3) If the bracket in the compiler is a left bracket , We'll just go into the stack ( The left bracket doesn't need to check for a match ); If it's right bracket , Just take out the top of the stack elements and check whether they match . 4) If the match , Out of the stack . otherwise , Just go back to false; // Code implementation var isValid = function(s){ let stack = []; var obj = { "[": "]", "{": "}", "(": ")", }; // Take out the brackets in the string for (var i = 0; i < s.length;i++){ if(s[i] === "[" || s[i] === "{" || s[i] === "("){ // If it's left parenthesis , Just into the stack stack.push(s[i]); }else{ var key = stack.pop(); // If the top elements are not the same , Just go back to false if(obj[key] !== s[i]){ return false; } } } return stack.length === 0 } 

So this requires a systematic training , Make special breakthroughs , Learning by category

For example, according to the classic data structure classification , Brush problem

  • Common data structures
  • Stack 、 queue 、 Linked list

  • aggregate 、 Dictionaries 、 Hash table

  • Common algorithms
  • recursive

  • Sort

  • enumeration

  • Algorithm complexity analysis

  • Algorithmic thinking

  • Divide and conquer

  • greedy

  • Dynamic programming

  • Advanced data structure
  • Trees 、 chart

  • Depth first and breadth first search

Vue The principle of response is introduced ,Object.defineProperty The defects of , Template compilation process , Resolve the template to AST, Optimize AST, take AST Convert to render function wait .

HOC What is it? ? comparison mixins What are the advantages

A lot of people see high-level components (HOC) The concept was startled , I think it's hard , In fact, the concept of this thing is really simple , Let's start with an example .

function add(a, b) { return a + b } // Now if I want to give this add Function to add an output function , Then you might consider me using it directly console.log Isn't that true . That's right. , But if we want to be more elegant and easy to reuse and extend , We can do that : function withLog (fn) { function wrapper(a, b) { const result = fn(a, b) console.log(result) return result } return wrapper } const withLogAdd = withLog(add) withLogAdd(1, 2) // In fact, this method is called higher-order function in functional programming , Everybody knows React There is functional programming in the idea of , Higher order components and higher order functions are the same thing . We implement a function , Pass in a component , Then implement another function inside the function to extend the incoming component , Finally, a new component is returned , This is the concept of higher-order components , The purpose is to reuse code better . // Actually HOC and Vue Medium mixins The effect is consistent , And in the early days React Is also used mixins The way . But in use class After creating the component in the same way ,mixins It can't be used , And actually mixins There are also some problems , such as : It implies some dependency , For example, I wrote something in the component state And in mixin Used in , There's a dependency here . In case someone else wants to remove it next time , I have to go mixin Find dependencies in Multiple mixin There may be functions with the same name in , At the same time, functions with the same name cannot appear in code components , Otherwise it's rewriting , In fact, I always think that naming is really a troublesome thing .. Snowball effect , Although I still use the same component mixin, But one mixin Will be used by multiple components , There may be a need for mixin Modify the original function or add more functions , This may create a maintenance cost HOC These problems were solved , And they have the same effect , It's also more politically correct ( After all, it's more functional ). 

Talk about specific projects

Usually in the interview , Like one side 、 On the other hand, we will ask about the specific projects we have done , And then it's asking for the details of the project . Generally, these problems may arise

  1. Find a project on your resume , Let me introduce you to this project

  2. Let's remind you of the projects you've done , It's worth sharing ( The biggest / The most difficult / It's the best expression of technical ability / The most unforgettable ) Of

  3. If you're asked to design xx System / project , How would you go about it

This kind of comprehensive problems related to the project , It can reflect the technical level of the candidate 、 Business level and architecture capability , It can also tell if a candidate has actually done a project , You can also find some soft skills of candidates .

How to deal with

  • First, the items in your resume , You must have chosen it carefully , You can't just pick a few , Be well prepared , Items in your resume , It should reflect the technical difficulty , And think about the details . Generally, a project can be introduced in several steps

  • Introduce the background of the project

  • Why is this project done , What was the background of the environment ? Or a project set up to solve a problem ? Background is very important , If you don't know the background , Listen to a concluding project as soon as you come up , The interviewer may be interested in the technical selection of the project 、 There will be misunderstandings in technical difficulty , Even wonder if there has ever been such a project .

  • For example, as soon as they come up, they say : Our project uses 「backbone」 To make the frame , then ... and 「backbone」 It's a relatively new technology three or four years ago , Now there are better options , If you don't introduce the time background of the project , The interviewer must be in a daze .

  • Take on the role
  • What are the roles of the people involved in the project , What's your role in it ?

  • People here tend to dig holes for themselves , For example, exaggerate their role in the project . Generally speaking , When interviewers ask for details , If the candidate can explain the details or technical solutions clearly 、 clear , Whether he did it or with someone else , Or think about it , Can reflect the candidate's technical level and technical vision . The premise is to do the right thing within your control 「 beautify 」.

  • Final results and benefits
  • During the project introduction , The final results and benefits of the project should be presented , For example, how long did the project go online after development , What's the data after going online , Whether it meets the expectation , Or it brings new problems , When they meet problems, how do they remedy them .
  • Very important : Summary and reflection of the project
  • What are the gains ?

  • Is there anything we can't do enough , How to improve ?

  • Whether it can be migrated ?

  • There is summary and reflection , There will be progress . After the project is finished, there are often some experiences and experiences , It's time to talk to the interviewer . When sorting out the summary and reflection of the project , Follow the list below to sort out :

  • such as , I've described a project in detail before , There seemed to be no problem with the project at that time , But now there's a better solution , The candidates should be here : Now it seems , This project also has xx The problem of , I can get through xx To solve the problem .

  • Another example : When doing this project , What you do better , It can be migrated to other projects and used directly , As small as code snippets , Big to solutions , There will always be something worth summarizing and combing .

  • After introducing the project summary , It can also guide the interviewer to think in the field he is good at . For example, the problems mentioned above in the project , You can lead to what you are good at , Even if the interviewer doesn't ask , You also introduced .

Follow the four paragraphs above to introduce the project , It will make the interviewer feel that the candidate has a clear idea , Understanding and thinking of the whole project , It can also summarize and reflect on the benefits and problems of the project , a 「 One arrow, three carvings 」.

How to do without a large project

For fresh graduates who have just been looking for a job , Or the interviewer asks you to design a large project , Candidates may not have similar experience . Don't use it at this time 「 I won't 、 I haven't 」 In a word .

If it is, there is no project , Then you can mention your daily hand training projects , Or see a solution article / book , One of the projects mentioned , Express your thoughts .

If it's for a project that the interviewer has asked you to design / System , Think about it in the following steps :

  • Have you ever met a similar project

  • Have you ever read an article about a similar solution

  • Can the project be disassembled , In the process of dismantling, can you find that the projects you have done can be used

  • What is the problem solved by the project , Is there a better solution to this kind of problem

All in all , Remember not to say 「 I do not know! 、 I haven't 」 Just give up , Every time you ask a question, it's an opportunity to show yourself .

Questions about project details and technical points

In the process of introducing the project , The interviewer may ask for technical details , So when we were preparing for the interview , We should try to sort out the technical details , Technical details include :

  • Technology selection scheme : At that time, the situation of technology selection

  • Technical solutions : The reason for the final determination of a technical solution , such as : Choose to use Vue It doesn't work React What is it for? ?

  • Project data and revenue

  • The hardest part of the project

  • Pit met : If you use some kind of framework, you will encounter some pits

Generally speaking , The following factors need to be considered when making technology selection :

  • Time : Now, what's the hot technology , Why is it on fire , What problems have been solved , Can it be used in my project ?

  • The team : How familiar is an individual or team with a technology , What's the cost of learning ?

  • Business needs : What is the need , Can we apply the current mature solutions / Library to quickly solve ?

  • Maintenance cost : Whether a solution can be cover Within the confines of the living area ?

Data and revenue encountered in the project should be well tracked , Ensure the authenticity and credibility of the data . in addition , The pit you meet may be the one that the interviewer asks more , Especially some popular technologies now (Vue、React、webpack), The average team is using , So be sure to prepare in advance

Soft skills questions answer

  • toughness : Compressive ability , Be able to meet difficulties under certain project pressure , For example, the courage to take the initiative and solve technical problems

  • conscientiousness : For projects you've done , To be able to appear bug Take the initiative to solve

  • Continuous learning ability :IT Industry is an industry that needs constant charging , especially Web The front end has been changing all these years , So continuous learning ability is very important

  • Teamwork ability : It's not personal heroism to do a project , You should be part of the team , Fighting with the team

  • Communication skills : We often meet with communication needs and interaction design work , Should be willing to communicate and share

Think about the most difficult colleagues you've ever met , How do you communicate with him

Generally speaking , I always meet one or two people I don't like at work , In this case, conflicts should be avoided as much as possible , Start with yourself and let the other party feel the spirit of cooperation .

therefore , Meeting difficult colleagues , Don't rush to report to the leaders , You should take the initiative to do more , For example, planning work arrangements , Let him choose what he does , When you have a conclusion, please send an email to confirm it , In this way, your leaders and other members will understand the work arrangement , While whipping each other , We also have clear responsibilities . In the project , Take the initiative to check the progress of the project , Identify overdue issues ahead of time .

The point is to highlight : The consciousness of actively communicating and solving problems , Instead of looking for leaders when problems arise .

When you are assigned a task that is almost impossible to accomplish , What would you do

In this case , It is generally solved in the following way :

  1. Look up the information yourself first , Looking for solutions , Assess what resources you need to complete , How long does it take?

  2. Can we solve the problem with the help of colleagues around us

  3. Take the analysis results and give feedback to the superior , Ask for help or resources

Outstanding soft skills : Analyze and solve problems , Communicate and ask for help .

What do you do in your spare time ? Besides code writing, what else do you like

This kind of question is also the interviewer's high frequency question ,「 A person's spare time determines his future 」, If you answer that you are chasing dramas and playing games on weekends and so on , It seems to be too unproductive .

Generally speaking , Recommend the following answer :

There are generally three states on weekends :

  1. Go to sports with friends , And get together and chat , Talk about new technologies and things like that ;

  2. I will also read some books to charge , Like what I saw recently xx, I have some ideas ;

  3. Sometimes I'm bored at home. I'll do a small project or realize a small function with the hot technology recently .

Such an answer , He can show his sunny side and be good at social communication , I can also show my ambition .

Interview notes

Ask questions

Interview is a two-way choice , So after the interview, there will be a question session . During the question period , Candidates had better not ask nothing , Don't just ask about salary 、 Whether to work overtime or not .

In fact, this time you can ask the interviewer about the team 、 The business that the team does 、 The specific work of this position 、 Work planning , Even some data ( Maybe some questions will not be answered directly ).

You can also ask questions about training opportunities and promotion opportunities in the company . If it's high-end jobs , You can ask : Their own leader What kind of people do you want to assign this position to , How long do you want to be able to reach .

Summary and thinking after the interview

After the interview, summarize where you are not doing well , Where to do well , Write it all down , In the future, we will develop our strengths and avoid our weaknesses

author :Vam The golden bean road

Main areas : The front-end development

My WeChat :maomin9761

WeChat official account : The road ahead

This article is from the official account of WeChat The road ahead original, If there is any infringement , Please contact to delete .


  1. HTML + CSS + JavaScript to achieve cool Fireworks (cloud like particle text 3D opening)
  2. HTML + CSS + JavaScript realizes 520 advertising love tree (including music), which is necessary for programmers to express themselves
  3. Solve the problem of Web front-end deployment server (it can be deployed online without a server)
  4. HTML + CSS + JS make wedding countdown web page template (520 / Tanabata Valentine's Day / programmer advertisement)
  5. What else can driverless minibus do besides "Park connection"?
  6. Cloud native leads the era of all cloud development
  7. NRM mirror source management tool
  8. Bring it to you, flex Jiugong
  9. Lolstyle UI component development practice (II) -- button group component
  10. Deconstruction assignment in ES6
  11. Luo 2 peerless Tang clan was officially launched. The official gave a key point, and the broadcast time was implied
  12. 20初识前端HTML(1)
  13. 当新零售遇上 Serverless
  14. 20 initial knowledge of front-end HTML (1)
  15. When new retail meets serverless
  16. [golang] - go into go language lesson 5 type conversion
  17. [golang] - go into go language lesson 6 conditional expression
  18. HTML5(八)——SVG 之 path 详解
  19. HTML5 (8) -- detailed explanation of SVG path
  20. 需要开通VIP以后页面内容才能复制怎么办?控制台禁用javascript即可
  21. Web前端|CSS入门教程(超详细的CSS使用讲解,适合前端初学者)
  22. 实践积累 —— 用Vue3简单写一个单行横向滚动组件
  23. Serverless 全能选手,再下一城
  24. What if you need to open a VIP to copy the page content? Just disable JavaScript on the console
  25. Web front end | CSS introductory tutorial (super detailed CSS explanation, suitable for front-end beginners)
  26. Practice accumulation - write a single line horizontal scroll component simply with vue3
  27. Dili Reba is thin again. She looks elegant and high in a strapless hollow skirt, and her "palm waist" is beautiful to a new height
  28. Serverless all-round player, next city
  29. The difference between MySQL semi synchronous replication and lossless semi synchronous replication
  30. Vue表单设计器的终极解决方案
  31. The ultimate solution for Vue form designer
  32. Nginx从理论到实践超详细笔记
  33. Yu Shuxin's red backless swimsuit is split to the waist and tail, with a concave convex figure and excessive color matching, and his face is white to dazzling
  34. Nginx ultra detailed notes from theory to practice
  35. 【动画消消乐|CSS】086.炫酷水波浪Loading过渡动画
  36. typecho全站启用https
  37. CCTV has another popular employee. The off-site interpretation is very professional, and the appearance ability is no less than that of Wang Bingbing
  38. [animation Xiaole | CSS] 086. Cool water wave loading transition animation
  39. Enable HTTPS in Typecho
  40. 50天用JavaScript完成50个web项目,我学到了什么?
  41. 根据JavaScript中原生的XMLHttpRequest实现jQuery的Ajax
  42. What have I learned from completing 50 web projects with JavaScript in 50 days?
  43. "My neighbor doesn't grow up" has hit the whole network. There are countless horse music circles, and actor Zhou Xiaochuan has successfully made a circle
  44. 根据JavaScript中原生的XMLHttpRequest实现jQuery的Ajax
  45. Implement the Ajax of jQuery according to the native XMLHttpRequest in JavaScript
  46. Implement the Ajax of jQuery according to the native XMLHttpRequest in JavaScript
  47. 30 + women still wear less T-shirts and jeans. If they wear them like stars, they will lose weight
  48. 数栈技术分享前端篇:TS,看你哪里逃~
  49. Several stack technology sharing front end: TS, see where you escape~
  50. 舍弃Kong和Nginx,Apache APISIX 在趣链科技 BaaS 平台的落地实践
  51. Abandon the landing practice of Kong and nginx, Apache apisik on the baas platform of fun chain technology
  52. 浪迹天涯king教你用elementui做复杂的表格,去处理报表数据(合并表头,合并表体行和列)
  53. 前端HTML两万字图文大总结,快来看看你会多少!【️熬夜整理&建议收藏️】
  54. Wandering around the world king teaches you to use elementui to make complex tables and process report data (merge header, merge table body rows and columns)
  55. 路由刷新数据丢失 - vuex数据读取的问题
  56. Front end HTML 20000 word graphic summary, come and see how much you can【 Stay up late to sort out & suggestions]
  57. Route refresh data loss - vuex data reading problem
  58. Systemctl系统启动Nginx服务脚本
  59. Systemctl system startup nginx service script
  60. sleepless