Quick mastery of JavaScript interview Basics (iii)

Source: Internet
Author: User
Tags set time hasownproperty

Translator by: summed up a lot of JavaScript basic knowledge points, very useful!

    • Original: The Definitive JavaScript Handbook for your next developer interview

In order to ensure readability, this paper uses free translation rather than literal translation. In addition, the copyright of this article belongs to the original author, translation is only used for learning.


JavaScript is the most popular programming language since 2014, according to the StackOverflow survey. Of course, this is understandable, after all, 1/3 of the development work requires some JavaScript knowledge. So if you want to be a developer, you should learn the language.

The main purpose of this blog is to summarize the concepts that are common in all interviews, so that you get to know them quickly and easily. (as the content of this article is too long and easy to read, it will be divided into three blogs to translate, this is the third part.) The first part please click on the quick Master JavaScript interview Basics (i))

New keyword

If you use new a keyword to invoke a very special form of a functional type. We call those new functions called constructors (constructor function).

What has been new done with the functions used?

    • To create a new object
    • Sets the prototype of an object to the prototype of the constructor
    • Executes the constructor, this executes the newly constructed object
    • Returns the object. If the constructor returns an object, the constructed object is returned.
To get a better understanding of the underlying, we define the new keyword
Mynew (constructor, ... arguments) {
var obj = {}
Constructor.prototype);
Constructor.apply (obj, arguments) | | Obj
}

What is the new difference between using and not using?

 function bird (  this.wings = 2; 
/* normal function call */
let fakebird = Bird ();
console.log (Fakebird); //undefined
/* using new call */
let realbird= new Bird ();
console.log (realbird) //{wings:2}

To facilitate comparative understanding, the translator adds additional tests for a situation:

Mbird () {
This.wings =
"Hello";
}

New Mbird ();
{Wings:2}

You will find that this sentence return "hello" does not take effect!

Prototypes and inheritance

The prototype (Prototype) is the most confusing concept in JavaScript, and one of the reasons is that it prototype can be used in two different situations.

    • Prototype relationship
      Each object has an prototype object that contains the properties of all its prototypes.
      .__proto__is an irregular mechanism (provided in ES6) that is used to get the prototype of an object. You can understand that it points to an object parent .
      All ordinary objects inherit the .constructor property, which points to the constructor of the object. When an object is implemented through a constructor, the property points to the constructor of the constructor __proto__ .prototype . Object.getPrototypeOf()is the standard function of ES5, which is used to get the prototype of an object.

    • Prototype properties
      Each function has a .prototype property that contains all the attributes that can be inherited. The object contains properties that point to the original constructor by default .constructor . Each object created using the constructor has a constructor property.

The following example helps to understand:

functionDog (Breed, name) {
This.breed = breed,
THIS.name = Name
}
Dog.prototype.describe =function) {
Console.log (`${THIS.name} is a${This.breed} ')
}
Const RUSTY =New Dog (' Beagle ',' Rusty ');

/* The prototype property contains the constructors and the properties defined on prototype in the constructor. */
Console.log (Dog.prototype){describe:?, constructor:?}

/* objects constructed using the dog constructor */
console.log (Rusty) //{breed: "Beagle", Name: "Rusty"}
/* property or function inherited from the prototype of the constructor */
//"Rusty is a Beagle"
/*. __proto__ attribute to the constructor. Prototype Property */
//{describe:?, constructor:?}
/*. constructor attribute point to constructor */
console.log (rusty.constructor) //? Dog (breed, name) {...}
/span>

the use of JavaScript can be said to be quite flexible, in order to avoid the bug does not know, it may be possible to access the Fundebug online real-time monitoring .

Prototype chain

Prototype chain refers to the link between objects through prototype, forming a direction of the chain. When accessing a property of an object, the JavaScript engine first checks to see if the object contains the property. If not, find out if the object's prototype is included. And so on until the property is found or the last object is found. The prototype of the last object is null by default.

Owning vs Inheritance

An object has two properties, each of which is itself defined and inherited.

functionCar () { }
Car.prototype.wheels =4;
Car.prototype.airbags =1;

var MyCar =New Car ();
Mycar.color =' Black ';

/* the properties in the prototype chain can also be viewed by in: */
' airbags ' in myCar) //true
console.log (mycar.wheels) //4
< Span class= "built_in" >console.log (mycar.year) //undefined

/* to see if this property is owned by hasOwnProperty: */
console.log (Mycar.hasownproperty ( ' airbags ')) false-inherited
console.log (Mycar.hasownproperty ( ' color ')) //true

Object.create(obj)Creates a new object, prototype points to obj .

4};
Object.create (dog);

Console.log (Mydog.hasownproperty (///False
4
True
Inheritance is a reference pass value

Inherited properties are all referenced in the form of a reference. We use examples to understand the image:

var Objprot = {Text' Original '};
var Objattachedtoprot =Object.create (Objprot);
Console.log (Objattachedtoprot.text) //Original

We change the Text property of Objprot, and the Text property of Objattachedtoprot also changes the
Objprot.text = ' prototype property changed ';
Console.log (Objattachedtoprot.text) //prototype property changed

But if we say that a new object is assigned to Objprot, then the Objattachedtoprot Text property is unaffected
Objprot = { text: ' replacing property '};
Console.log (Objattachedtoprot.text) //prototype property changed

Classic Inheritance vs prototype inheritance

Eric Elliott's article is described in great detail: Master the JavaScript interview:what ' s the difference between Class & Prototypal inheritance?
The author believes that prototype inheritance is superior to classic inheritance and provides a video introduction: https://www.youtube.com/watch?v=wfMtDGfHWpA&feature=youtu.be

Asynchronous JavaScript

JavaScript is a single-threaded programming language, meaning that the JavaScript engine can only execute a piece of code at a time. The problem is that if a piece of code takes a long time to execute, the rest of the operation gets stuck. JavaScript uses call stack to record the invocation of a function. A call stack can be seen as a stack of books. The last book is on top and is first removed. The first books are at the bottom, and the last one is removed.

To avoid complex code taking up CPU too long, one solution is to define an asynchronous callback function. Let's define an asynchronous function ourselves to see:

 function greetingasync (name, callback) {
let greeting = "Hello," + name;
SetTimeout (_ = callback (greeting), 0);
greetingasync (console.log);
console.log (

We greetingAsync construct the statement in greeting , and then by setTimeout defining the asynchronous, callback function, is to let the user to define the specific way of greeting. For the sake of convenience, we use it directly console.log .
The above code execution first prints start greeting , and then it is hello, fundebug . In other words, greetingAsync the callback function executes after. In web development, when interacting with a server, it is necessary to constantly send various requests, while a page may have dozens of requests. If we request and wait for the result one by one in order, the serial execution will cause the page to load very slowly. Asynchronously, we can send the request first and then process the request result in the callback, efficiently and low concurrency.

Here's an example to describe the entire execution process:

Const FIRST =function () {
Console.log (' First message ')
}
Const SECOND =function () {
console.log ( ' Second message ')
const third = function ( console.log ( ' third message ')
first ();
settimeout (second, 0);
third ();

//output:
/ /First message
//third message
//Second message
  1. In the initial state, the browser console has no output and the event manager is empty;
  2. first()is added to the call stack
  3. will be console.log("First message") added to the call stack
  4. console.log("First message")Execute and output "first message" to the console
  5. console.log("First message")To remove from the call stack
  6. first()To remove from the call stack
  7. setTimeout(second, 0)Add to Call stack
  8. setTimeout(second, 0)execution, after 0ms, second() is added to the callback queue
  9. setTimeout(second, 0)To remove from the call stack
  10. third()Add to Call stack
  11. console.log("Third message")Add to Call stack
  12. console.log("Third message")Execute and output "third message" to the console
  13. console.log("Third message")To remove from the call stack
  14. third()To remove from the call stack
  15. Event Loop second() moves from the callback queue to the call stack
  16. console.log("Second message")Add to Call stack
  17. console.log("Second message")Second message "to the console
  18. console.log("Second message")To remove from the call stack
  19. Second()To remove from the call stack

It is important to note that the second() function does not execute immediately after 0ms, and that the time you pass into setTimeout() the function and the second() time of execution is not necessarily directly related. The event manager waits setTimeout() for the set time to expire before it is added to the callback queue, and the time it executes in the callback queue is related to the execution time of the function it was in before it was in the queue.

More
    • Quick mastery of JavaScript interview Basics (i)
    • Quick mastery of JavaScript interview Basics (II.)

Copyright NOTICE: Please specify the author fundebug and this address:https://blog.fundebug.com/2018/01/29/ the-definitive-javascript-handbook-for-a-developer-interview-3/

Quick mastery of JavaScript interview Basics (iii)

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.