JavaScript: A few easy-to-be-wrong points to interview frequently

Source: Internet
Author: User
This article for everyone to share about-javascript: Interview frequently appear several easy wrong point, hope to help everyone

1. Preface

This time, gold three silver four, many people interview, many people share face questions. In the previous period, I also temporarily as an interviewer, in order to understand the level of the interviewer, I also wrote a topic, interviewing a few front-end developers. In this period of time, I am learning, in writing design patterns of some knowledge, unexpected design patterns of these knowledge, is the face of the test, frequently let people drop the pit. So, to summarize today, those who let people fall out of the pit.

2. Object-Oriented Programming

regarding object-oriented and process-oriented, the individual feels that the two are not absolutely independent, but rather mutually complementary relationships. As to when to use object-oriented, when with the process-oriented, specific circumstances, specific analysis.

For object-oriented programming. There is a Gao Zan answer:

Object-oriented: Dog. Eat (excrement)
Process oriented: eat. (dog, excrement)

But this example is not very elegant, I changed, give an elegant small example to illustrate the object-oriented and process-oriented differences.

Requirements: Define ' waiting to eat hotpot '

Object-oriented thinking is: waiting. Action (eat hotpot)

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

Code implementation aspects:

Object-oriented//define person (name) let People=function (name) {    this.name=name;} Action people.prototype={    eat:function (someThing) {        console.log (' ${this.name} Eat ${something} ');}    } Waiting is an individual, so to create a person (new once people) let shouhou=new people (' waiting ', ' male ', ' X '), Shouhou.eat (' hotpot ');//process-oriented let Eat=function (who, someThing) {    console.log (' ${who} Eat ${something} ');} Eat (' Waiting ', ' hotpot ');

The results are the same, are output ' waiting to eat hotpot '. But in case I'm full now, I'm ready to write the code. How does this come true? 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 (' waiting ');

The same result: ' Waiting to write code '

But it is not difficult to find object-oriented more flexible, reusability and extensibility more. Because object-oriented is the object (in the example: ' Waiting ') to perform certain actions. These actions allow you to customize the extension.
The process is defined by a number of actions that specify who will perform the action.

Well, the simple object-oriented description is here, as for the three main object-oriented features: inheritance, encapsulation, polymorphic this self-surfing to find information.

3.this

When developing with JavaScript, many developers are more or less this pointing to the ring, but in fact, about this the point, remember the core of the sentence: which object calls the function, the function inside the object to which to point.

Here are a few things to talk about

3-1. Normal function calls

There is no special accident in this case, that is, pointing to the global object-window.

Let username= ' waiting ' function fn () {    alert (this.username);//undefined}fn ();

Maybe everyone will be confused, why not output 守候 , but in a closer look, I declare the way is let that will not be the window object
If the output waits, write like this

var username= ' Waiting ' function fn () {    alert (this.username);//Waiting for}FN ();//---------------window.username= ' waiting ' function fn () {    alert (this.username);//Waiting for}FN ();

3-2. Object function Invocation

This belief is not difficult to understand, that is, the function call, where this point

Window.b=2222let obj={    a:111,    fn:function () {        alert (THIS.A);//111        alert (this.b);//undefined    }} Obj.fn ();

Obviously, the first time is obj.a the output, which is 111. And the second time, obj there is no b such attribute, so the output undefined is this pointing obj .

But the following is a good situation to note

Let obj1={    a:222};let obj2={    a:111,    fn:function () {        alert (THIS.A);    }} Obj1.fn=obj2.fn;obj1.fn ();//222

This belief is not difficult to understand, although obj1.fn it is from the obj2.fn assignment, but the call function is obj1 , so this point to obj1 .

3-3. Constructor calls

Let Testclass=function () {    this.name= ' 111 ';} Let Subclass=new TestClass (); Subclass.name= ' Waiting '; Console.log (subclass.name);//Waiting Let subclass1=new testclass (); Console.log (Subclass1.name)//111

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

But there is a pit, although generally not appear, but it is necessary to mention.

Returns an object inside the constructor, returning the object directly, not the object created after the constructor is executed

3-4.apply and call calls

In simple terms, apply and call will change the this of the incoming function.

Let obj1={    a:222};let obj2={    a:111,    fn:function () {        alert (THIS.A);    }} Obj2.fn.call (OBJ1);

At this point, although it is obj2 called method, but used call , the dynamic this point to obj1 . The equivalent obj2.fn of this execution environment is obj1 . applyand call details are mentioned below.

3-5. Arrow function call

The first thing to say is that ES6 provides an arrow function that increases our development efficiency, but inside the arrow function, no this , the arrow function this is inherited outside the environment.

An example

Let obj={    a:222,    fn:function () {            setTimeout (function () {Console.log (THIS.A)})    }};obj.fn ();// Undefined

It is not difficult to find that although the this in fn () is pointing to obj , however, the normal function passed to setTimeout , this point is window< /c5>, there is no a under window , so here output undefined .

Switch to arrow function

Let obj={    a:222,    fn:function () {            setTimeout (() =>{console.log (THIS.A)});    }};o Bj.fn ();//222

This output 222 is because, to setTimeout is the arrow function, and then the arrow function does not have this, so to the upper scope to find, in this case, the upper-level scope of the setTimeout is fn. And the This in fn points to obj , so the setTimeout inside of the arrow functions This, pointing to obj. So the output 222 .

4.call and apply

calland apply The effect is exactly the same, the only difference is on the parameters above.
callThe parameters received are not fixed, the first parameter is a this pointer to the body of the function, the second parameter is passed in sequence.
Apply receives two parameters, and the first parameter is also a this pointer to the body of the function. The second argument is a collection object (an array or an array of classes)

Let Fn=function (a,b,c) {console.log (a,b,c);} Let arr=[1,2,3];

As the above example

Let obj1={    a:222};let obj2={    a:111,    fn:function () {        alert (THIS.A);    }} Obj2.fn.call (OBJ1);

callAnd apply two main uses are

1. this direction of Change (turn this from obj2 point to obj1 )

2. Method borrowing ( obj1 no fn , just borrowing obj2 method)

5. Closures

Closures this may be confusing for everyone, but the concept must be conquered! Here's a simple example.

Let add= (function () {Let Now=0;return {doadd:function () {    now++;    Console.log (now);}}) ()

And then execute it several times!

As a result, now this variable is not recycled as the function executes, but is kept in memory.
Specific reasons: just started to come in, because it is the automatic execution function, the first step in will automatically execute, this piece

and assign the object to the add . Because add there are functions that are dependent on now this variable. So now will not be destroyed, recycled. This is one of the uses of closures (continuation variable cycles). Because now it is not accessible outside, this is another use of closures (creating local variables to protect local variables from being accessed and modified).

There may be doubts that closures can cause memory leaks. But everyone wants to, the above example, if you do not need to close the packet, you need to use global variables. The effect is consistent by placing the variable inside the closure and placing it in the global variable. Using closures can also reduce global variables, so the above example closures are better!

6. Summary

Learning design patterns, the knowledge points encountered are these, these knowledge points, but also i in group chat, community inside, let people drop pits more test center. This knowledge, can be said to develop commonly used, interview often test the knowledge, or suggest you go into some study. It's easy to go over there. Not in depth. If you have any suggestions for the article, please advise.

Related recommendations:

About the front end interview (ii)

Ask the most 10 JavaScript front-end interview questions

Front-end interview treasure Pure Welfare

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.