Recently I saw some people sharing the 16th front-end Jinali (group leader of front-end learning group) and the 17th front-end Hangzhou Harvest offer (excellent passer-by).

Just as the 17 th I also recently took two offers easy, but I see they write the title of the answer is not very detailed, so I also want to share with you of obsessive-compulsive disorder, I will put all didn’t hang up and hang up things to share, with a detailed analysis of every subject, so the article is a bit long.

Long article carefully into ha, but there are wine and story, small bench I have moved for you, sit down!

The story begins

I had planned to change my job after the Chinese New Year, but some time ago, a headhunter wrote me a message from Jane, saying that my writing was good and asking me if I wanted to change my job. So I updated my resume, sent it in, invited me for an interview, but the company was in Beijing/Xi ‘an, didn’t show up, but that’s where the story started, and that’s where I started changing jobs.

Post a few articles that you think are well written:

CSS3 animation caton performance optimization solution

In-depth analysis of 0.1 +0.2===0.30000000000000004 reasons

How to solve the 0.1 +0.2===0.30000000000000004 problem

Remember a simple DOM XSS attack experiment

Do you really understand the difference between == and ===?

Classic CSS pit: How to achieve perfect vertical horizontal center?

Junior from his summer internship to work more than half a year now, is close to 1.5 + years, already tied to the front development domain, the work and the study of high strength type, buy a book test, write code to see, writing a blog blog, ask questions to answer the question, the total sum is almost a freshman to junior learning time time to study the front-end development.

Recently, I started the written test and the interview. Although I didn’t make much preparation, I easily got an offer from a company founded by Ali, a zhejiang University company. In addition, I was praised by the third interviewer yesterday.

As I change my job this time, I hope to stay in a company for at least 2 years. I really hope to explore and study the interesting front-end world with a group of friends who have insights, thoughts and pursuits about front-end technology. So I decided to try more interviews and join a team that was more suitable for me.

At the same time, I also hope that through this interview sharing, I can give some encouragement to the front-end partners who work as hard as I do, and I also hope to show you the most true myself.

(1) God rewards those who work hard

After rejecting the first company that reached out to me, another Ariz startup sent me a private message in BOSS Direct and went in with a test-level mentality. The on-site written test was not good, but when they saw that my simple essay was ok, they asked me to redo the questions: some excellent interview questions [0], and the extension of the last word and string matching question, which were all guided by the interviewer step by step, I felt that I had learned a lot.

The senior said that I have a strong learning ability, so he was willing to give me this opportunity and offered me a salary 2K higher than now. The key is that I heard that there are many projects available. It is said that the boss who interviewed me was also a technical expert in Ali.

Post a question and my answer below.

1. Describe the design pattern you are familiar with 2. Describe the module mechanism you understand 3. The most familiar frame routing mechanism 5. State management 6. Count the number of words in a stringCopy the code

1. Describe a design pattern you are familiar with

The design patterns I’m most familiar with: Factory Pattern (ES5), Component Design Pattern (ES6) Factory Pattern (ES5, based on Prototype). In this case, Base class, subclass Factory)

var Factory = function () { if(! (this instanceof Factory)){ return new Factory(); } } Factory.prototype = Object.assign(new Base(), { version: '0.0.1 defaultOption: {title:' title '}, init: function (CFG) {this. Title = CFG. Title | | '. this.currentOption = Object.assign(this.defaultOption,{ //... }) }, render: function () { var option = this.currentOption; this.chart.setOption(option); }, showTitle: function () { this._showTitle(); }})Copy the code

The React component design pattern (ES6, class-based, easy to inherit and initialize) is my favorite. In this example, the parent class Compnent, the subclass Retrive)

class Retrive extends Component { constructor (props) { super(props); this.state = { name:'' }; this.getRemoteData = this.getRemoteData.bind(this); } getRemoteData (data) { this.state.retriveResult = data; } render(){return (<div className="Retrive"> <Button name="search" onClick={this.getremotedata}> query </Button> </div>); }}Copy the code

2. Describe the module mechanics you understand

AMD: asynchronous module loading specification. A. Js, define a component that relies on jQuery and ECHRTS.

define(['jquery', 'echarts'], function ($, echarts) { var AMD = function(){} AMD.prototype = { title:'', foo: Function baz(){} function baz(){} return {main:AMD, bar: bar } });Copy the code

This can be done if B.js depends on A.js

Define (['./a'], function (a) {foo var instance_amd = new a.ain (); Instance_amd.foo () // call bar a.bar()});Copy the code

ES6 modules: The package mechanism is similar to Python: import import, export export.

1. Scenario: Vue, React Recommended mechanism, need to escape Babel into ES5 to be compatible with browsers. 2. About the import... (from...) 1. An import... from... The from command can be followed by many path formats. If you give only vue, axios and other package names, node_modules will be loaded automatically. If the relative path and file prefix are given, search the specified location. You can load a variety of files:.js,.vue,.less, etc. ③ We can omit from this book. 3. About export ①, export can be objects, expressions, functions, and classes ②. Is derived in order to let others into 4. Speech as an aside: use es6, has a special good rules to follow, an es6 specification (https://github.com/airbnb/javascript)Copy the code

CommonJS: nodejs is used a lot in nodejs, and the keyword is require. No node package is written, and only other modules are referenced, so the internal implementation principle is not clear.

3. The principle of MVVM

MVVM is a software architecture pattern that facilitates the separation of the front and back ends. View: The View layer, roughly known as the DOM. Model: The Model corresponding to the database, usually in JSON format, communicates with the database through HTTP (S) as the body of reQ. ViewModel:View and Model are bidirectional bound through ViewModel.

The core is to provide two-way data binding between the View and the ViewModel, so that the ViewModel changes and the View changes immediately. MVVM front-end implementation: Angular, Vue, react.

Common data bidirectional binding in VUE.

view:{{message}}
viewModel v-model="message"
model:message
Copy the code
<div id="app-6"> <p>{{ message }}</p> <input v-model="message"> </div> var app6 = new Vue({ el: '#app-6', data: { message: 'Hello Vue! '}})Copy the code

In a single file component, there is an additional TEMPLATE tag in HTML5 that wraps the View and viewModel, and the Model part stays in the Script part.

<template> view viewModel </tamplate> <script> model </script> <styles>Copy the code

In the process of using react, I have never heard of bidirectional binding, so I was deeply impressed by redux Reducers’ recommendation to write it as a pure function. If it is a pure function, I think it should have the meaning of a single data flow.

Speaking of frameworks, one of the most interesting things for me is the communication between components. For simple components, which only involves parent-child communication, Vue uses on EMIT and React uses props. Vuex is recommended for vue and Redux is recommended for react. The unified global state tree is very good for state management and makes logic very clear. Vue project file structure research is not deep, react project file structure, presentational and containers design methods feel very reasonable, one is responsible for view and the other is responsible for data, very clean.

4. The most familiar framework routing mechanism

Vue routing dependencies: Vue-Routers compose single-page applications by combining components that need only be mapped to routes. That’s the core of front-end routing — changing the view without making a request to the back end. Note the difference between the two modes: Hash mode and history mode. Hash mode will add an ugly # after the hash mode. How the Hash mode works: The hash mode has the following features: Although the hash mode appears in the URL, it is not included in the HTTP request. It has no impact on the back end, so changing the hash mode does not reload the page. Hash can be interpreted as an anchor point, such as./index.html/#/foo, where the hash value is #/foo so that the page is not jumped. This is equivalent to unifying different anchors of a page, and jumping between pages is similar to./index.html/#foo to./index.html/#bar.

./store/index.js

import Router from 'vue-router'
Vue.use(Router)
export default new Router({
  routes: [
  {
  path: '/common',
  name: 'common',
  component: Common
  }
]

Copy the code

Will also include embedded routines by routing level, dynamic routing and redirect, equivalent to imitate the mode of browser requests and server responses, actually does not involve backend requests, the browser can be achieved only page jump, some time ago I do user access control is used to vue – the router, compared the MVC structure under the back-end routing, clear a lot. So the back end is just responsible for the route writing API.

5. Status management

Here are some thoughts I had while working on a project with Vuex, briefly revised, and also added some thoughts about Redux.

Vuex State, front-end data View, front-end DOM actions, user operations, data changes, resulting in DOM changes.

Multiple components (view) Shared state: popular, is can communication between multiple components, from back-end data changes, when the component is large, if brother communication between components depend on the parent component to communicate, can lead to very high coupling between components, which can lead to project logic chaos, difficult to maintain.

Multiple components (views) depend on the same state. Actions from different views need to change the same state.

Global singleton mode management, which extracts the shared state of components no matter where in the component tree, any component can obtain state or trigger behavior!

Practice is the mother of wisdom:

2.getters stored in getter.js, data flow is state→getter→ component. A getter is equivalent to a data capture filter that takes specific data from the repository to the component and is equivalent to centralized processing of computed. Mutations → State; mutations is equivalent to a data submission emitter, which submits data from the component to the warehouse. 4. Actions Are stored in actions.js. Data flow is component →actions→mutations→state, which is the main place for asynchronous operation. Modules are used when developing large applications. Each module has its own States, getters, Actions, and mutation, and has a nodeJS flavor.Copy the code

Vuex three Principles:

The only way to change the state in Vuex's store is to commit mutation.Copy the code

Be sure to note the difference between mutation and action!

Mutation only changes the local state, that is, only the data in the store is modified directly. The action contains asynchronous operations that call the API directly, pass the data from the API, and then commit mutation.

Action is only one more operation than mutation that calls the API asynchronously, since it usually returns two states, succes, error, or promise, depending on the mutation.

In redux, a component dispatches an action to a store, which is equivalent to sending an HTTP request, and the store responds with a response to the component. Similar to Vuex, the only difference is that Vuex also requires the introduction of React-Redux, and the introduction of Providers and connect components and stores.

6. Count the number of words in the string

“Hi how are you I am fine thank you YouTube am am”, count the number of times “you” appears.

function wordCount(str,word){ var str = str || ""; var word = word || ""; var strArr = str.split(" "); var count = 0; for(var i=0; i<strArr.length; i++){ if(word===strArr[i]){ count++ } } return count; } wordCount("hi how are you i am fine thank you youtube am am","you");Copy the code

What if the string has no Spaces?

function wordCount(str,word){ var str = str || ""; var word = word || ""; var count = 0; var index = str.indexOf(word); while(index! ==-1){ count++; str = str.substr(index+word.length); index = str.indexOf(word) } return count; } wordCount("hihowareyouiamfinethankyouyoutubeamam","you");Copy the code

What if, instead of using the js built-in string function, you compare each character yourself?

function wordCount(str,word){ var num = 0; var str = str+" " || ""; var word = word || ""; var strArr = str.split(""); var wordArr = word.split(""); var count = 0; function compare(arr1,a,arr2,b){ if(b+a<arr2.length){ if(arr1[a]===arr2[b+a]){ num++; return compare(arr1,a+1,arr2,b+1) } if(num===arr1.length){ count++ num = 0; } } } for(var i=0; i<strArr.length; i++){ for(var j=0; j<wordArr.length; j++){ if(wordArr[wordArr.length-1]===strArr[i+wordArr.length-1]){ compare(wordArr,0,strArr,i+0) } } } return count; } wordCount("hihowareyouiamfinethankyouyoutubeamam","am");Copy the code

Could it be more efficient?

function wordCount (str,word) { var str = str+" " || ""; var word = word || ""; var strArr = str.split(""); var wordArr = word.split(""); var wordArrLen = wordArr.length; var count = 0; var num = 0; function compare (arr1,a,arr2,b) { if(b+a<arr2.length){ if(arr1[a]===arr2[b+a]){ num++; return compare(arr1,a+1,arr2,b+1) } if(num===arr1.length){ count++; num = 0; } } } var j = 0; while(j<wordArrLen){ var i = 0; while(i<strArr.length){ if(wordArr[wordArrLen -1]===strArr[i+wordArrLen -1]){ compare(wordArr,0,strArr,i+0); } i++; } j++; } return count; } wordCount("hihowareyouiamfinethankyouyoutubeamam","a"); //1. Adjust the highest level traversal group from 37 ^ 2 to 3 ^ 2, from 1369 to 9 //2. Merging control variables and control conditions, using while instead of for, removes the consumption of the JS engine to query the presence of I and j, which slightly reduces the code readability //3. The local variable wordArrLen is assigned to the repeatedly referenced wordArrLen, where array.prototype. length is reduced from 3 queries to 1Copy the code

Don’t worry about the road ahead without friends, the world who do not know you

I didn’t want to continue looking, but today a friend gave me a suggestion that I could find a better job by applying for more jobs before changing my job. Then I thought of seeing so many job postings on V website, so I just tried again to see if there was a better one.

Resume: Front-end development – Simple Book – While you’re still young 233

Jane: While you are still young

Making: FrankKai

SegmentFault: While you’re young

Coordinates: Hangzhou

Then I posted on V website, and a V friend added my friend and arranged a telephone interview. After understanding the technical atmosphere of the company and negotiating the salary, I successfully got the offer, and the salary is similar to that of the first company, which is a company from Zhejiang University.

I had a great conversation with the interviewer, and we even talked about eating chicken in the end. The phone interview was so enjoyable that I can only remember one cross-field question so far. The interviewer of the third company was also very nice. It was cold, so he reminded me of the freezing on the road, but since the third interview is not until tomorrow night, I have put together the BOSS hiring questions of the third company: some excellent interview questions [1]

Post a question and my answer below.

1. Have you ever encountered cross-domain problems? 2. What does the following code output? 3.["1","2","3"]. Map (parseInt) returns what? 4. What is the color of "in" in the code below?Copy the code

1. Have you ever encountered cross-domain problems?

When it comes to cross-domain issues, it must be said that homology, what is homology, same protocol, same domain name, same port, that is, homology.

Communication between different sources can have cross-domain problems. Typically, a client accesses a server on which cross-domain is configured. For example, when I use AXIos, vue’s official recommended asynchronous request library, to request the back-end service opened by KOA, I will encounter cross-domain problems. For example, KOA can rely on KOA-CORS. Specifically, Access-control-allow-origin: access-Control-allow-origin: access-Control-allow-origin: access-Control-allow-origin Or traditional Maven or Nginx, can be easily configured across domains.

Has JSONP ever worked? JSONP hasn’t used it yet, but it seems to work by loading a script DOM tag through JS and then importing the code you want to execute in the SRC of the new script. In fact, cross-domain problems have a similar effect on the back end, but it’s called interprocess communication, and there’s IPC, RPC, and so on.

2. What does the following code output?

let O = function(name){
 this.name = name || 'world';
};
O.prototype.hello = function(){
 return function(){
  console.log('hello ' + this.name);
 };
};
let o = new O;
let hello = o.hello();
hello();
Copy the code

My young answer was: Hello world.

The trap is that when o.prototype. hello is called, it returns a function. In this case, this becomes window when the hello method of o is executed.

So the answer is hello undefined?

Young you were wrong again. It wasn’t.

But the hello.

Note that it is hello, not hello undefined, but an empty string

The reason is that window.name is predefined and its value is null.

If you don’t believe me, you can print window.name on the console and it will return “”. Try printing window.yourname again, such as window.frank, and it will return undefined.

Thanks to @ygh1 for reminding, the print result is also relevant to the running environment, because node is global, browser is global window.

The global object in node does not have an initial name attribute.

So the correct answer would be:

Node environment: hello undefined browser environment: hello _____(non-zero wide empty characters)Copy the code

In my work, more common factory functions like the one above are written like this.

let O = function(name){
 this.name = name || 'world';
};
O.prototype.hello = function(){
  console.log('hello ' + this.name);
};
let o = new O("frank");
let hello = o.hello("frank");
Copy the code

The output is hello Frank.

If frank is not passed in, the default value printed is Hello world.

3.[“1″,”2″,”3”]. Map (parseInt) returns what?

[1,1,1] A. [1,2,3] B.[“1″,”2″,”3”] C.[1,1,1] D. other

This is another one of those stupid traps that I’ve seen before when I was looking at MDN’s map function.

The correct answer is D: other.

What are the other values? [1, NaN, NaN].

Believe it, why not cute [1,2,3]?

[root@localhost] [root@localhost] [root@localhost] [root@localhost] [root@localhost] [root@localhost] [root@localhost] [root@localhost] [root@localhost] [root@localhost] [root@localhost] [root@localhost] [root@localhost] But index is not ignored, so 0,1,2 are passed to parseInt as the second argument.

If that doesn’t make sense, let’s break each step of [“1″,”2″,”3”].map(parseInt) apart.

ParseInt ("1",0) converts the character "1" to base O. Since base 0 does not exist, return 1 of type Number. ParseInt ("2",1) converts the character "2" to base 1, and returns NaN because base 1 is exceeded. ParseInt ("3",2) now converts the character "3" to a base 2 number, and returns NaN because the base 2 number is exceeded.Copy the code

At this point, the truth is out. What are the common ways to write a map without traps?

[“1″,”2″,”3”].map(x=>parseInt(x))

Pass in a complete function with arguments and callback, so as not to cause errors due to arguments passed in incorrectly, and return a nice new array that has been processed purely by the function.

In fact, if you go a little bit further here, you can look at what is a pure function?

A pure function is actually a function that does not change the input, but can use the input to generate a new output function that takes the input as raw material and outputs a new output after processing. The key is not to change the input. Pure function is a skill point that the reducer of REdux must have.

ParseInt returns 1 with +”1″ and 2 with +”2″. Daniel as expected, black technology is really much.

4. What is the color of “in” in the code below?

<ul class="list" id="list"> <li class="favorite"> <span> </span> </li> <li class="favorite"> <span Class ="highlight"> </span> </li> </ul> <style> # list. favorite:not(#list). } #list .highlight:nth-of-type(1):nth-last-of-type(1){ color: blue; } </style>Copy the code

A. red B.blue C.black

My answer is: LET me guess, probably A, because A has the largest weight, and the pseudo-class selector should have A smaller weight.

The interviewer sent an 👍. Can you come to the company for an interview tomorrow? I have an interview scheduled for tomorrow.

So that’s the end of this problem, because I’m really really not interested in CSS, so please forgive me.

Interview -3 failed

Font-size: 16px! Important; “> < font size =” font-size: 16px! Important;

em rem

In order to ensure that users change the font size, keep the font size in the vertical direction the same. Different from PX, both are font size units. In other words, the font size needs to be calculated and converted to PX. The RPX of wechat mini program is also the same, and finally converted to PX, probably borrowing from REM’s idea.

But EM is relative to the inherited parent element, and REM to the root element. Listen to Daniel said, REM is used more in China, may be the use of habit problems. I also think rem is easier to use. Assign an initial value to the font size of the root element, and then use CSS media query to dynamically change the global unit. It is very convenient to use, but THE readability of EM is very poor. You have to go up level by level. It’s not intuitive.

In modern browsers, 1rem equals 16px, but can be controlled by HTML {font size:percentage/num}.

Compare two REM and EM examples.

HTML abbreviation structure:

<html>
    <body>
        <div></div>
    </body>
</html>
Copy the code

Rem examples:

HTML {the font - size: 62.5%; } /* =10px */ body {font-size: 2.0rem; } /* =20px */ div {font-size: 1.0rem; } /* =10px */Copy the code

Em examples:

HTML {the font - size: 62.5%; } /* =10px */ body {font-size: 2.0em; } /* =20px */ div {font-size: 1.0em; } /* =20px */Copy the code

The font-size section of MDN gives a very good explanation of EM and REM. The Original English version is very intuitive. Here I will post again:

em

Represents the calculated font-size of the element. If used on the font-size property itself, it represents the inherited font-size of the element.

rem

Represents the font-size of the root element (typically ). When used within the root element font-size, it represents its initial value (a common browser default is 16px, but user-defined preferences may modify this).

In fact, EM and REM are somewhat similar to the communication between components of the MVVM framework, with concepts of hierarchical inheritance and global impact. Em is passed level by level, that is, inheritance. The same is true for props and event subscription and publishing in the framework. The transmission of props, father and grandson needs to be passed level by level. Rem, however, is similar to the state management library in the framework, such as Vuex and Redux. It extracts a global state tree, which can be directly transmitted to grandson if grandpa wants to teach grandson, instead of complicated inheritance.

2. Implement timed traffic lights with only one DIV

<! DOCTYPE HTML > < HTML lang="zh-cn"> <head> <meta charset=" utF-8 "/> <title> 0%{ background-color: green; left: 0; 33.3%} {background - color: green; left: 0; 33.4%} {background - color: yellow; left: 200px; 66.6%} {background - color: yellow; left: 200px; 66.7%} {background - color: red; left: 400px; 99.9%} {background - color: red; left: 400px; } } .traffic-light{ position: relative; width: 200px; height: 200px; border-radius: 50%; animation: light 3s ease-in-out 0s infinite; } .container{ width: 600px; border:10px solid #000; border-radius: 20% 20%; } </style> </head> <body> <div class="container"> <div class="traffic-light"></div> </div> </body> </html>Copy the code

Interview -4 failed

Due to a variety of reasons, began a new round of interviews, this round of interviews can be said to be fruitful. Communication with all kinds of interviewers, in addition to the harvest of some omissions of knowledge points, found that the interview is actually very test the level of the interviewer. Figure out how to be a good front end interviewer.

And very important elder brother’s experience: the preparation that must be done before entering big factory, brush a month in advance.

1. SetTimeout and function call stack

console.log(1); setTimeout(function(){ console.log(2); }, 0); console.log(3);Copy the code

SetTimeout’s callback is an asynchronous function. Can refer to this function call stack parts: blog.risingstack.com/node-js-at-…

2. Promotion priority of function foo and var foo

console.log(typeof foo);
var foo = "foo";
function foo(){}
Copy the code

Output: the function

console.log(typeof foo);
function foo(){}
var foo = "foo";
Copy the code

Output: the function

Function takes precedence over var, overriding var declarations of the same name either before or after it.

3. Let block scope and setTimeout

for(let i=0; i<6; i++){ setTimeout(function(){ console.log(i) },0) } console.log(i)Copy the code

Output:

0
Uncaught ReferenceError: i is not defined
1
2
3
4
5
Copy the code
  • Uncaught ReferenceError: i is not defined

This shows that the block scope of the for statement is valid not only in curly braces but also in parentheses.

  • Output 0, 1, 2, 3, 4, 5

SetTimeout’s callback is an asynchronous function. The for loop is essentially an asynchronous loop queue. SetTimeout’s callback will be called five times.

Why is the printing order out of order during debug? Log breakpoint to console.log(I).

Uncaught ReferenceError: i is not defined
0 
2
5
4
3
1
Copy the code

What if we replace let with var?

for(var i=0; i<6; i++){ setTimeout(function(){ console.log(i) },0) } console.log(i)Copy the code

Output: 6 6 Reasons:

  • It prints window.i

Each I passed in refers to the same I, and the window. I values are 1,2,3,4,5,6, but all are the same reference. By the time the function call stack starts executing the setTimeout callback, window. I has changed to 6

  • Var does not limit block scope

No six separate address Spaces are allocated to setTimeout’s callback

Why does object.tostring. call([1,2,3]) return [Object Array]? [].toString() can return [object Array]?

To answer this question, need deep understanding of the Object. The prototype. ToString. Call ().

Call [1,2,3] as an argument to object.tostring. It isn’t. Wouldn’t direct object.tostring ([1,2,3]) do the same? Can’t. There is also array.proto.tostring (), so you can call arr.tostring () directly. Can you detect this? I can’t.

Then what is the reason? Let’s start with a chart.


The data type example return
string “foo”.toString() “foo”
digital 1.toString() Uncaught SyntaxError: Invalid or unexpected token
Boolean value false.toString() “false”
undefined undefined.toString() Uncaught TypeError: Cannot read property ‘toString’ of undefined
null null.toString() Uncaught TypeError: Cannot read property ‘toString’ of null
String String.toString() “function String() { [native code] }”
Number Number.toString() “function Number() { [native code] }”
Boolean Boolean.toString() “function Boolean() { [native code] }”
Array Array.toString() “function Array() { [native code] }”
Function Function.toString() “function Function() { [native code] }”
Date Date.toString() “function Date() { [native code] }”
RegExp RegExp.toString() “function RegExp() { [native code] }”
Error Error.toString() “function Error() { [native code] }”
Promise Promise.toString() “function Promise() { [native code] }”
Obejct Object.toString() “function Object() { [native code] }”
Math Math.toString() “[object Math]”

Why does the following happen?

Object.toString.call(Array)//"function Array() { [native code] }"
Object.prototype.toString.call(Array)//"[object Function]"
Copy the code

Here’s the answer!

Object.toString()//"function Object() { [native code] }"
Object.prototype.toString()//"[object Object]"
Copy the code

Object and its prototype chains each have a toString() method, the first of which returns a function and the second a value type.

If we know that the different, now we’ll analyze the Object. The prototype. ToString. Call (Array) / / “[Object Function]”. The Array Object itself returns a constructor, Array / / ƒ Array () {} [native code], and the Object. The prototype. The toString () returns the / / “[Object Type]”, in the form of Array by call this context switch to the Object, and call the Object. The prototype. The toString (), therefore return [Object Function].

Note that math.tostring () returns “[object Math]” directly.

The actual development, we used the most might be: Object. The prototype. ToString. Call ([1, 2, 3]) / / “[Object Array]” the.

Conclusion:

  • In general, toString() of an object in js returns a string whose content is related to function declaration syntax, such as [1,2,3].tostring ()//”1,2,3″
  • //”function Array() {[native code]}”
  • Built-in functions tend to return a similar “[native code]” the body of the function, need to cooperate with the call method, such as the Object. The prototype. ToString. Call ([1, 2, 3]) / / “[Object Array]”

So can’t Array directly. The prototype. ToString. Call ([1 4])? No way! Because of the Array, the Function, although the Date is based on the Object is created, but they are inherited Object. The toString (), rather than the Object. The prototype. The toString (). One more impression:

Object.toString()//"function Object() { [native code] }"
Object.prototype.toString()//"[object Object]"
Copy the code

So this is must use the Object. The prototype. The toString () to determine type of reason.

As for the Object. The prototype. The toString () is how to implement internal, wait until the time is right to go further.

5. How can I help you

var obj = { a: 1, name: 'world', objSayName: function (fn) { fn(); } } function sayName () { return console.log(this.name); } obj.objSayName(sayName); // output: undefinedCopy the code

Why is that? Inside objSayName of obj, there is no modification of this to refer to the current calling object.

Use the same global Function for multiple objects (local methods). Simplify: Use global methods (local methods) to reuse global methods: Modify this reference, using function.prototype.bind () to explicitly modify this reference to the current calling object. The reason: Calling f.bind(someObject) creates a new function with the same body and scope as f, but where this occurs in the original function,in the new function it is permanently bound to the first argument of bind, regardless of how the function is being used.bind only works once!

var obj = { name: '1', objSayName: function (f) { var g = f.bind(this); console.log(g()); }}; function sayName(){ return this.name; } obj.objSayName(sayName);Copy the code

Output: ‘1’

What if a global method wants to print local properties of an object? Apply: The same global function outputs multiple objects (internal variables) Compact: the global function outputs local (variables) methods: Use apply or call to modify this to refer to the called object reasons: An object can be passed as the first argument to call or apply and this will be bound to it.

var obj = { name: '1', say: function (fn) { fn(); }}; function sayName(){ return this.name; } sayName.apply(obj); sayName.call(obj); // Output: '1'Copy the code

Reference: developer.mozilla.org/en-US/docs/…

The whole world is mine, my life is like a song

The interview questions of my current employer are the ones I most appreciate. I have worked here for nearly a year and have grown up a lot.

The topic is mainly divided into four parts:

  • HTML
  • CSS
  • JS
  • code

The answers are not verified for accuracy and need to be verified and updated. I will answer them from the perspective of “1 year before” and “today”, which is also a record of my own growth.

HTML

1. Please describe the differences between cookies, sessionStorage and localStorage

1 year before: Cookies, need to work with the back end, a form of authentication, expires time sessionStorage, current session valid localStorage, local cache, expires time today:

cookies
  • An HTTP cookie (Web cookie, browser cookie) is a small piece of data that the server sends to the user’s Web browser.
  • The browser can store it locally and send it to its data source server on the next request.
  • A typical application scenario is to determine whether two requests are from the same server —- from the same logged-in user, which is a stateful memory of the stateless HTTP protocol.
sessionStorage
  • Key /value storage, session storage
  • Maintains a separate storage area for each given Origin, available during a page session
localStorage
  • Key /value storage, persistent storage
  • When the browser closes and opens again, the localStorage key-value pair still exists

2. Please explain<script>,<script async>and<script defer>The difference between

1 year before: Common synchronization; Asynchronous; Lazy loading.

today:

  • <script async>Controls the browser to load scripts asynchronously. If async is set to false, the browser loads the script synchronously during HTML parsing. Generally through codedocument.creatElement()Insert scripts are asynchronous, and setting Async to false can control them to be synchronous.
  • <script defer>The defer attribute is used toControls whether scripts are executed after the HTML has been parsedBut will be inDOMContentLoadBurn before completion.

1. What is DOMContentLoaded? DOMContentLoaded event, which is triggered after initializing the HTML document to complete loading and parsing, without waiting for stylesheets, images, and frame to finish loading. The Load event is similar to the DOMContentLoaded event in that people often confuse the two events. 2. What is Load event? The load event is triggered after a full load has been completed. 3. How to solve the problem of synchronous JS blocking DOM rendering and render DOM at the fastest speed? Asynchronous JS, optimized stylesheets loading. 4. How to check whether the document has finished loading? Document. The readyState.

  • Loading.
  • The interactive document is loaded, the document has been parsed but sub-resources such as images, stylesheets, and frame relief are loaded.
  • The Complete Document and child resources are loaded, and the Load event is triggered.

Therefore, there are three states to load a document resource at a time: Loading ‘ ‘interactive and complete.

3. Why is it usually recommended to place CSS in<head></head>Between, while will js<script></script>Placed in the</body>Before?

1 year before: To prevent blocking browser rendering, perform CSSOM first, then draw DOM, then manipulate DOM. The main thread single-thread renders the UI.

From the perspective of technical implementation, today firstly loads stylesheets and draws, and then loads and executes JS files that may involve DOM operations after DOM rendering, so as to avoid rendering block caused by JS execution. From a user experience perspective, loading stylesheets first reduces the amount of time a user spends on blank pages and improves the user experience.

CSS

1. The difference between classes and IDS in CSS

1 year before ①ID has a high priority ② The ID is unique and must be unique

Today ① different syntax, #idname,.classname ② different elements, #idname for a single element,.classname for all elements ③ different selectors weight, #idname weight is higher than.classname

2. What are the ways to hide the DOM

1 year before

  • display: none
  • position: top right bottom left
  • transform
  • z-index
  • Remove THE DOM node (JS)

How do I hide DOM elements?

3. Please explain*{ box-sizing: border-box }What are the benefits of using it?

1 year before weird box model. Easy to calculate, width contains the border, responsive percentage layout.

Today box-sizing has two types of values: content-box and border-box. Content-box contains only content. The width of the border-box will include the content, padding, and border. For example, width:100% refers to the width of the content, padding, and border.

For example, if the padding and border of the child element inherit the width:100% of the parent element, the padding and border elements will overflow if box-sizing is content-box. Width :100% will comfortably include the padding and border.

Because there are many such application scenarios, we simply set all tags to border-box, and then manually set them to Content-box for special cases.

Set box-sizing to border-box for all elements.

4. How was the priority determined in the process of determining the style (please give an example)? How do I use this system?

1 year before

  • Style property<div style=""></div>
  • id
  • Tag name
  • class
  • pseudo-classes

Each selector has a weight of #foo>. Class ::before and id> tag >class> pseudo-class.

The Today priority goes from high to low

  • ! Important Not recommended practice
  • Inline style<span style=""></span>
  • ID selector #foo
  • Foo, property selector [type=”radio”], pseudo-class :hover
  • Type selectors p, SPAN, pseudo-elements ::before

An excellent illustration of CSS selector priorities:specifishity.com/

Universal selector (*), combination operators (+, >, ~ ‘, | |) and negative pseudo-classes (: the not ()) has no effect on weight.

5. Why use translate() instead of absolute positioning, or vice versa? Why is that?

1 year before absolute

  • Removed from normal document flow
  • Does not take up page layout space
  • Open a new stacking context
  • Affect other layout elements
  • Eliminating edge overlap

Reduced computation, translate() does not affect other elements, better performance, and fewer GPU computations

Today has the answer in my blog post: CSS3 Animation Caton performance optimization solution

Translate () involves the synthesizer thread, which is independent of the main thread, so it is faster. Absolute Positioning involves the main thread, which leads to the layout redrawing and JS execution of the main thread, so it will be slow.

JS

1.. What’s the difference between “call” and “apply”?

1 year before

  • Parameters are passed in different ways, but both dynamically modify the this context
  • Call has functions that perform stack operations
  • Apply simply passes arguments to the new class

Today wrote two blog posts on this topic: Function.prototype. how does apply work? How does function.prototype. call work? A) call B) apply C) call D) apply Call calls, apply applies, calls functions, and applies parameters, as can be seen from the literal meanings of call and apply. The main difference between Call and Apply is that Call simply switches this context to another class, thus calling methods that do not exist on its own; The main purpose of Apply is to pass other types of parameters into itself and then call its own methods.

Let’s say I have foo, bar. Foo. Call (bar) bar calls foo’s method, instance object.tostring ([1,2,3])->”[Object Array]”, and the Array instance calls Object’s toString method. Apply (null, bar) foo’s method applies bar arguments, math.max. Apply (null, [1,2,3])->3, Math’s Max method applies every argument in [1,2,3].

2. Explain how JSONP works and why it is not real Ajax?

Without calling the XMR object, the server allows the browser to pass a browser-defined function in the Query parameter, which may be overridden by an XSS attack.

The answer from StackOverflow high ticket: stackoverflow.com/questions/2…

JSONP is not a very complicated problem. Suppose we are under the example.com domain, and we want to send a request to the example.net domain. In order for the request to succeed, you need to cross domain boundaries, which is taboo for browsers.

One way around this limitation is the

Start entering JSONP. When you send a request to a JSONP-enabled server, you pass some special data about your page to the server. In this way, the server wraps the response in a way that is convenient for your browser to handle.

For example, the server needs a parameter called callback to enable the JSONP function. Your request will then want to like this: http://www.example.net/sample.aspx?callback=mycallback

In the absence of JSONP, this returns some basic JS objects such as {foo: ‘bar’}

However, with JSONP support, the server receives the callback argument, which wraps the result differently, returning the following data: mycallback({foo: ‘bar’});

Just as you shrink, it will call browser-side methods. So, callback is defined as follows on your page:

mycallback = function(data){
  alert(data.foo);
};
Copy the code

Now, after the script loads successfully, it is evaluated and the function executes. Cross-domain request successful!

So there is a serious problem with JSONP: you lose control of requests. For example, there is no way to know the return of an error code. You can use timers to monitor requests, but that’s not good. JSONRequest is a great way to execute cross-domain scripting, secure, and gain more control over the request.

In 2015, CORS was a viable alternative to JSONRequest. JSONP is still useful in older browsers, but not secure. CORS is a more secure and efficient way to do cross-domain request access.

3. Have you used javascript templating? What libraries have you used?

1 year before jade vue angular react { … } or {{… }}

Today: Some great template engine libraries

I’m only familiar with vue.js, so I didn’t list react and Angular demos.

4. What’s the difference between == and ==?

I have blogged about this issue and read the specification. ①=== is a subset of == ②== has type conversions ③ There are different implementations in the specification today do you really understand the difference between == and ===?

5. Please explain Javascript’s same-origin policy.

1 Year before The browser security mechanism

  • Same-origin: same protocol, same host, and same port
  • Cross-domain issues: CORS can be set up backend to allow cross-origin-access information

Today’s understanding of same-Origin policy

6. Do you use Promises and polyfills? Write down the basic use of Promise (ES6)

1 year before axios

  • axios get() post()
  • Front-end request and response interceptor

today

  • Promise.all() returns a Promise only when all asynchronous promises are in the Resolved state
  • Promise.prototype.catch() catches exceptions caught during Promise execution
  • Promise. Prototype. Finally () is the catch, and then, often used for running the code in the catch, and then, to avoid repetition
  • Promise.prototype. Then () Promise completes execution, proceed to the next step
  • Promise.race() promises return the first resolve or reject Promise in the Promise set; Here’s my post: When do I use promise.race ()?
  • Promise.reject() The Promise class catches exceptions
  • Promise.resolve() The Promise class resolves the data

7. What are the pros and cons of using Promises instead of callbacks?

1 year before Fixed callback hell.

Today loads the canvas with an image resource.

class CanvasImage {
  constructor(url, width, height) {
    this.width = width || 500;
    this.height = height || 500;
    this.url = url || ' ';

    this.element = new Image(this.width, this.height);
  }
  get imageElement() {
    return this.element; }}Copy the code

The callback hell way

source.onload = function() {
  const target = new CanvasImage(url, 80.80).imageElement;
  target.onload = function() {
    const main = new MainCanvas(source, target, 'right').canvasElement;
    context.drawImage(main, 0.0.500.500);
  };
};
Copy the code

Promise way

const sourcePromise = new Promise((resolve) = > {
  setTimeout(() = > {
    const target = new CanvasImage(url, 80.80).imageElement;
    resolve(target);
  }, 0);
});
source.onload = function() {
  sourcePromise.then((target) = > {
    const main = new MainCanvas(source, target, 'right').canvasElement;
    context.drawImage(main, 0.0.500.500);
  });
};
Copy the code

Async/await

 function sourceCanvasImage() {
  return new Promise((resolve) = > {
    setTimeout(() = > {
      const target = new CanvasImage(url, 80.80).imageElement;
      resolve(target);
    }, 0);
  });
}

async function mergeCanvas() {
  const targetElement = await sourceCanvasImage();
  const main = new MainCanvas(source, targetElement, 'right').canvasElement;
  context.drawImage(main, 0.0.500.500);
}

source.onload = function() {
  mergeCanvas();
};
Copy the code

8. What is event loop?

1 year before

  • Principle of asynchronous
  • Event subscription, event publishing
  • Asynchronous non-blocking events

Today’s official explanation is more authoritative: nodejs.org/de/docs/gui…

What is an Event Loop? The Event loop allows Node.js to perform non-blocking I/O operations —– although JS is single-threaded —– by offloading operations to the kernel as much as possible.

Because most modern kernels are multithreaded, they can handle multiple operations in the background. When one of these is complete, the kernel tells Node.js that an appropriate callback can be added to the poll queue and executed.

Node.js Event Loop, Timers and Process.nexttick ()

Event Loop, principle details include the following

  • call stack
  • (macro)task queue
  • microTask queue
  • background thread

The first three sections belong to the main thread. Read the Node source code to find out. The last background thread belongs to the part of Libuv, so you can go into the source code of Libuv (which is a C language library specially dealing with async) to understand its implementation mechanism.

But reading the source code requires a very good foundation. Here recommended above contains a knowledge very go heart of the article: blog.risingstack.com/node-js-at-…

code

1. What is the value of foo?

var foo = 10 + '20';

1 year before: 30

today: “1020”

2. How to implement the following functions?

add(2.5);/ / 7
add(2) (5);/ / 7
Copy the code

1 year before Array object via arguments class.

function foo(){
    var sum = 0;
    for(var i = 0; i<arguments.length; i++){
        sum += arguments[i]
    }
    if(arguments.length>=2) {return sum;
    }else{
        returnfoo; }}Copy the code

Add (2)(5) The operation fails.

today

const add = (a, b) = > {
    const result =
      a && b
        ? a + b
        : function(b) {
            return a + b;
          };
    return result;
 };
Copy the code

3. What are the results of the following two alerts?

var foo = "Hello";
(function() {
    var bar = " world"; alert(foo + bar); }) (); alert(foo + bar);Copy the code

1 year before “undefined World” “Hello undefined”

Uncaught ReferenceError: bar is not defined // The global scope cannot access local variables

4. What is the output of the following code?

console.log('one');
setTimeout(function() {
    console.log('two');
}, 0);
console.log('three');
Copy the code

1 year before one three two

today one three two

Cause: The task in function call stack is executed first, setTimeout is put into macro task queue and executed later. Event loop includes call Stack, (macro) task queue, microtask queue and background Thread, while ordinary code in call Stack is preferentially executed. SetTimeout will enter macro task queue through background thread. Macro task queue Interval executes microtask queue.

5. What is the output of the following code?

function getResult(value, time){
    return new Promise((resolve) = >{
        setTimeout(() = >{
            console.log(value);
            resolve();
        }, time);
    });
}
(async() = > {const a = getResult(1.300);
    const b = getResult(2.200);

    await a;
    awaitb; }) (); (async() = > {await getResult(1.300);
    await getResult(2.200); }) ();Copy the code

1 year before 1 2

today 2 1 1 2

How to understand async function?

6. What is the following code output?

var obj = {
    a: 1.name: 'world'.objSayName: function(fn) { fn(); }}var name = 'hello';
var arr = [1.2.3.4.5];

function foo(o) {
    var bar = arr || [6.7.8];
    var arr = [4.2.9];
    var baz = o;
    baz.a = 2;
    console.log(bar, obj.a);
}

function sayName() {
    return console.log(this.name);
}

foo(obj);
obj.objSayName(sayName);
Copy the code

1 year later [4,2,9] 2 ‘hello’

Today (June) 2 ‘hello’

Reason: Variable promotion.

var bar,arr,baz;
bar = arr || [6.7.8];// arr is undefined, so bar is assigned [6, 7, 8]
arr = [4.2.9];
Copy the code

Baz gets the reference to obj, and all changes to baz are equivalent to changes to obj, so print 2.

Because of the closure, this in the global sayName function points to the global, so hello.

I want to be a strong person, so that the world is a little bit different because of me, even if only a little bit

Post the focus of your ideal team

1. Room for growth of personal front-end technology

For example, the guidance of the senior front-end to the primary front-end, and the learning and improvement among front-end team members are the most important. My goal is to become a developer with solid foundation and independent front-end technology insights in two years

2. The company’s emphasis on employee growth and progress

Such as new training, technology sharing, technology translation and so on

3. Is the overtime work of the company 996 or 10105 or arranged according to the project schedule

As long as a bunch of people are looking for the ultimate front-end, 996 is perfectly OK

4. Employee subsidies and benefits

Holiday allowances, union benefits

5. Performance appraisal and bonus

Such as performance appraisal, year-end bonus

I hope I can stay in a company for at least two years after this job change, so I need to know all these aspects clearly before making a decision, and I need to be cautious, hoping to join an interesting and strong team ~

Front-end development – Simple Book – While you are still young 233

As a final digression, 3 companies are using VUE and all asked me if I have used vUE…

That’s it !

While you’re young

January 31, 2018

Frozen into a dog of ice hangzhou

How to become a qualified interviewer?

  • Learn to listen

No matter how many career issues an interviewer may want to share with you, listen to them without interrupting them

  • Learn to locate

A brief assessment of the interviewer’s abilities based on his or her work experience and context, although occasionally biased, can be helpful for follow-up questions

  • Learn to understand

Understand what the interviewer is trying to say, even if it’s vague, and try to capture what the interviewer is trying to say

  • Learn to guide

When the interviewer encounters a tricky topic, if the other side logic is not clear, learn to simplify complex, from the shallow to the deep to do guidance; Assume that the other person is comfortable with the topic at hand, lead to further principles or expand on application scenarios

  • Learn to mining

Learn to bring out the best in a candidate. Intelligence and persistence are all very good qualities

  • Learn to respect

When a candidate is anxious to hear what the interviewer thinks of him or her, whether or not you are happy with him or her, take the “we’ll let you know if there are any updates” approach

  • Learn to silence

When an interviewer wants to know what you think of a question, don’t go into too much depth

I am looking forward to communicating with you and making progress together. Welcome to join the technical discussion group I created which is closely related to front-end development:

  • SegmentFault technosphere :ES new specification syntax sugar
  • SegmentFault column: Be a good front-end engineer while you’re still young
  • Zhihu column: Be an excellent front-end engineer while you are still young
  • Github blog: Personal blog 233 while You’re Still Young
  • Front-end development QQ group: 660634678
  • excellent_developers

Strive to be an excellent front-end engineer!