1. Introduction

This time, golden three silver four, many people interview, many people share interview questions. Some time ago, I was also a temporary interviewer. In order to get a general idea of the level of the interviewees, I also wrote a topic and interviewed several front-end developers. During this period of time, I was learning to write some knowledge of design patterns, unexpected design patterns of these knowledge, is the interview questions, often make people fail the test point. So, today, to sum up, those who fail the test points.

2. Object-oriented programming

Regarding object orientation and process orientation, I personally feel that the two are not absolutely independent, but mutually reinforcing. As for when to use object oriented, when to use process oriented, specific situation, specific analysis.

Object oriented programming. There is a highly praised answer on Zhihu:

Object oriented: dogs. Eat (shit) Face process: eat.(dog, shit)

But that’s not a very elegant example, so I’m going to change it to a little more elegant example of the difference between object orientation and process orientation.

Requirement: Define ‘waiting for hot pot’

The object – oriented idea is: waiting. Action (eating hot pot)

Process-oriented thinking is: action (waiting, eating hot pot)

Code implementation aspects:

// Object oriented
// Define the person (name)
let People=function(name){
    this.name=name;
}
/ / action
People.prototype={
    eat:function(someThing){
        console.log(`The ${this.name}eat${someThing}`); }}// Waiting is a person, so create a person (new time People)
let shouhou=new People('wait'.'male'.24);
shouhou.eat('hot pot');

// Process oriented
let eat=function(who,someThing){
    console.log(`${who}eat${someThing}`);
}
eat('wait'.'hot pot');Copy the code

The result is the same, both output ‘waiting to eat hot pot’. But what if I’m full now and ready to write code. So how do we do that? Look at the code

// Object oriented
shouhou.coding=function(){
    console.log(this.name+'Write code');
}
shouhou.coding();
// Process oriented
let coding=function(who){
    console.log(who+'Write code');
}
coding('wait');Copy the code

Same result: ‘Waiting to write code’

But it’s not hard to find that object orientation is more flexible, reusable and extensible. Because object orientation is about performing some action against an object (‘ waiting ‘in the example). These actions can be customized for extension. Procedural orientation is defining a bunch of actions that specify who is going to perform that action.

Ok, that’s enough for a brief description of object orientation, as for the three main features of object orientation: inheritance, encapsulation, and polymorphism.

3.this

When developing in JavaScript, many developers are somewhat confused by the reference to this, but in fact, remember the most important thing about this reference: which object calls the function, and which object this refers to.

Let’s talk about it in a couple of ways

3-1. Plain function calls

There is nothing special about this case, it just points to the global object -window.

let username='wait'
function fn(){
    alert(this.username);//undefined
}
fn();Copy the code

You might wonder why I’m not printing wait, but if you take a closer look, I’m declaring let, not window if I’m printing wait, do I write it like this

var username='wait'
function fn(){
    alert(this.username);/ / waiting for you
}
fu();
//---------------
window.username='wait'
function fn(){
    alert(this.username);/ / waiting for you
}
fn();
// It's a good idea
//window.fn();Copy the code

3-2. Object function calls

That’s not hard to understand, is that function call, where does this point to

window.b=2222
let obj={
    a:111.fn:function(){
        alert(this.a);/ / 111
        alert(this.b);//undefined
    }
}
obj.fn();Copy the code

Obviously, the first output is obj.a, which is 111. And the second time, obj doesn’t have b, so undefined, because this refers to obj.

But here’s something to watch out for

let obj1={
    a:222
};
let obj2={
    a:111.fn:function(a){
        alert(this.a);
    }
}
obj1.fn=obj2.fn;
obj1.fn(a);/ / 222Copy the code

Fn is assigned from obj2.fn, but obj1 is called, so this refers to obj1.

3-3. Constructor calls

let TestClass=function(){
    this.name='111';
}
let subClass=new TestClass();
subClass.name='wait';
console.log(subClass.name);/ / waiting for you
let subClass1=new TestClass();
console.log(subClass1.name)/ / 111Copy the code

This is not difficult to understand, recall (new four steps) almost!

But there’s one pit, which doesn’t usually appear, but it’s worth mentioning.

Returning an object in a constructor returns the object directly, not the object created after executing the constructor

3-4. Apply and call

Apply and call are simply this that change the function passed in.

let obj1={
    a:222
};
let obj2={
    a:111.fn:function(a){
        alert(this.a);
    }
}
obj2.fn.call(obj1);Copy the code

Obj2 calls the method, but uses call to dynamically point this to obj1. Equivalent to this obj2.fn this execution environment is obj1. Apply and Call are detailed below.

3-5. Arrow function calls

First of all, WE have to say that ES6 provides arrow functions to increase our development efficiency, but in the arrow function, there is no this, the this in the arrow function inherits the external environment.

A case in point

let obj={
    a:222.fn:function(){    
        setTimeout(function(){console.log(this.a)})
    }
};
obj.fn();//undefinedCopy the code

This refers to window. There is no A under the window, so undefined is printed here.

I’m going to use the arrow function

let obj={
    a:222.fn:function(){    
        setTimeout((a)= >{console.log(this.a)}); }}; obj.fn();/ / 222Copy the code

This time 222 is printed because setTimeout is passed to the arrow function, and the arrow function doesn’t have this in it, so you have to look up the upper scope. In this case, setTimeout’s upper scope is FN. And fn’s this points to obj, so setTimeout’s arrow function this points to obj. So it prints 222.

4. Call and apply

Call and apply work exactly the same, except for parameters. Call takes a variable number of arguments. The first argument is a reference to this in the function body, and the second argument is passed in sequence. Apply takes two arguments, the first of which is also a reference to this inside the function. The second argument is a collection object (array or class array)

let fn=function(a,b,c){
console.log(a,b,c);
}
let arr=[1.2.3];Copy the code

Take this example above

let obj1={
    a:222
};
let obj2={
    a:111.fn:function(a){
        alert(this.a);
    }
}
obj2.fn.call(obj1);Copy the code

The two main uses of call and apply are

1. Redirect this (from obj2 to obj1)

2. Method borrowing (obj1 has no fn, just borrows obj2 methods)

5. The closure

Closure this may be confusing, but must be conquered concept! Let me give you a quick example

let add=(function(){
let now=0;
return {
 doAdd:function(){
    now++;
    console.log(now); }}}) ()Copy the code

Then do it a few times!

As shown in the figure above, the now variable is not recycled as the function completes execution, but is kept in memory. And the reason for that is, at the beginning, because it’s an autoexecute function, it’s going to autoexecute at the beginning, this one

And then assign that object to Add. Because there are functions in add that depend on the now variable. So now will not be destroyed, recycled. This is one of the uses of closures (to continue the variable cycle). Since now is not accessible from outside, this is another use for closures (creating local variables that protect them from being accessed and modified).

Closures can cause memory leaks, you might wonder. But if you think about the example above, if you don’t use closures, you use global variables. Putting variables inside closures has the same effect as putting variables inside globals. Using closures also reduces the number of global variables, so the above example closure is better!

6. Summary

When studying design mode, I met some knowledge points, these knowledge points, but also in my group chat, community, let people drop pit more test points. These knowledge, can be said to be the development of commonly used, often test the knowledge of the interview, or suggest that we learn in depth. I’m just going to go through it up there. Not really. If you have any suggestions on the article, please feel free to comment.

— — — — — — — — — — — — — — — — — — — — — — — — — gorgeous line — — — — — — — — — — — — — — — — — — — — want to know more, pay attention to focus on my WeChat public number: waiting for book cabinet