Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Share the test questions that JavaScript meets frequently.

2025-01-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly explains "sharing common JavaScript interview questions". The content of the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "sharing common JavaScript interview questions".

Please explain how this works in JavaScript.

First of all: this always points to the object in which the function runs, not the object in which the function is created. Anonymous functions or functions that are not in any object point to window.

1. Method invocation mode

When a function is saved as a property of an object, it becomes the method of the object. The value of this in the function is the object.

Var foo = {name: 'fooname', getName: function () {return this.name}} foo.getName (); / / this = > foo

2. Function call mode

When the function is not a property of the object. The value of this in the function is the global object

Note: the value of this in an internal function in a method is also a global object, not the this of an external function

Function foo () {this.name = 'fooname';} foo (); / / this = > window

3. Constructor invocation mode

Even if you call a function with new, where this will be bound to the newly constructed object.

Function Foo () {this.name = 'fooname';} var foo = new Foo (); / / this = > foo

4. Use apply or call to invoke the mode

When this mode is called, the this in the function is bound to the first parameter accepted by the apply or call method call.

Function getName (name) {this.name = name;} var foo = {}; getName.call (foo, name); / / this = > foo

The main way to change the value of this (as you can think of so far, welcome to add comments):

Force modification when the apply or call method is called so that the this points to the first parameter.

Use the Function.bind method to create a new function with the this in it pointing to the first argument provided.

Please explain the principle of prototype inheritance (prototypal inheritance).

JavaScript does not have the concept of "subclass" and "parent class", nor does it distinguish between "class" and "instance". It all depends on the "prototype chain" pattern to achieve inheritance.

Each function Sub has a property prototype,prototype that points to a prototype object, and there is also a property constructor in the prototype object that points to the function. An instance instance can be generated by new a function Sub. When calling a property or method of this instance, instance will first find whether it has this method or property. If not, it will look in the prototype prototype of the instance's constructor Sub, that is, Sub.prototype. If an instance superInstance of another type is assigned to the prototype object Sub.prototype, it is found in superInstance, where there is also an attribute prototype pointing to a prototype object, which goes up to Object.prototype at this level, thus forming prototype inheritance.

Using this principle, you can implement an inherits function by yourself:

Function inherits (subType, superType) {var _ prototype = Object.create (superType.prototype); _ prototype.constructor = subType; subType.prototype = _ prototype;}

Explain why the next piece of code is not IIFE (immediately called function expression): function foo () {} (); what changes should be made to make it IIFE?

(function fn () {..}) (), the function is enclosed in parentheses, becomes an expression, followed by a (), and executes the function immediately.

Some of the functions of IIFE:

Create a scope with code that holds a large number of temporary variables internally to prevent naming conflicts.

The outer layers of some libraries are wrapped in this form to prevent scope contamination.

Run some code that executes only once.

4. (function fn () {..}) (), the function is enclosed in parentheses and becomes an expression, followed by a (), and the function is executed immediately.

Some of the functions of IIFE:

Create a scope with code that holds a large number of temporary variables internally to prevent naming conflicts.

The outer layers of some libraries are wrapped in this form to prevent scope contamination.

Run some code that executes only once.

When a function is called, an execution environment and scope chain are created, and then initialized to form an active object based on arguments and other named parameters. After the end of the external function call, its execution environment and scope chain are destroyed, but its active object is saved in the closure, and finally destroyed after the closure function call. To put it simply, a closure is a function that can read internal variables of other functions. In js, a closure is a function that has access to variables in the scope of another function.

How to use: return the B function inside A function as the return value of A function.

Why:

1. Anonymous self-executing function

In some scenarios, functions only need to be executed once, such as functions such as init (), whose internal variables do not need to be maintained, and we can use closures. We create an anonymous function and execute it immediately, because the external cannot refer to its internal variables, so resources are released immediately after the function is executed without polluting the global object.

2. Encapsulation

Simulate the object-oriented code style for encapsulation, making it possible for private attributes to exist.

What is the difference between .call and .apply?

What .call and .apply have in common is that both are used to change the value of the this object in the function body.

The difference is that the second parameter is different. The second argument to apply () is an array object, arguments, which is passed in as an array, while call () is passed a series of parameters. For example

Math.max.call (null, 1,2,3,4); / / 4Math.max.apply (null, [1,2,3,4]); / / 4

6. Please explain Function.prototype.bind?

The Function.prototype.bind method creates a new function, and when the new function is called, its is value is the first argument passed to bind (), and its arguments are the other parameters of bind () and its original parameters.

7. Please point out the difference between JavaScript host object (host objects) and native object (native objects).

Host objects are DOM and BOM.

Native objects are Object, Function, Array, String, Boolean, Number, Date, RegExp, Error, Math and so on.

Please point out the difference between the following codes: function Person () {}, var person = Person (), var person = new Person ()?

Function Person () {}

Declare a function Person ().

Var person = Person ()

The result of the function Person () is returned to the variable person, and person is undefined if no value is returned.

Var person = new Person ()

New an instance object of Person.

Please explain how Ajax works in as much detail as possible. And what are the advantages and disadvantages of using Ajax?

Ajax is a way to get data from the server without refreshing the page.

Ajax makes an asynchronous request to the server through the XmlHttpRequest object, gets data from the server, and then uses javascript to manipulate the DOM update page.

Process

Create a XMLHttpRequest object.

Sets the callback function that responds to the HTTP request.

Create a HTTP request and specify the corresponding request method, url, and so on.

Send a HTTP request.

Gets the data returned by the server.

Use the JavaScript operation DOM to update the page.

Shortcoming

Unfriendly to search engines

It is expensive to realize the backward and backward function under Ajax.

Cross-domain problem limitation

Please explain variable declaration promotion (hoisting).

The prefix to the declaration of a variable is to raise the declaration of the variable to the forefront of the current scope.

The declaration front of a function promotes the entire function to the front of the current scope (after the preceding variable declaration).

/ / variable declaration prefix console.log (num); / / undefinedvar num = 1; equivalent to / / variable declaration prefix var num;console.log (num); / / undefinednum = 1

Please describe the event bubbling mechanism (event bubbling).

Event bubbling (event bubbling), which occurs at the beginning of the event from the triggered element, and then propagates up the DOM tree to the document object. If you want to stop the event from bubbling, you can use e.stopPropagation ().

What is "use strict"? What are the advantages and disadvantages of using it?

Advantages

Eliminate some imperfections in Javascript syntax and reduce some weird behaviors

Eliminate some unsafe places in the running of the code and ensure the safety of the running of the code.

Improve compiler efficiency and increase running speed

Lay the groundwork for future new versions of Javascript.

Shortcoming

The strict pattern changes the semantics. Relying on these changes can lead to problems or errors in browsers that do not implement strict mode.

Please explain JavaScript's homology strategy (same-origin policy).

The same origin policy restricts how text or scripts loaded in one source (origin) interact with resources from other sources (origin). The same origin means that the protocol, domain name and port are the same, and the same origin policy is a security protocol.

Please explain how JSONP works and why it is not a real Ajax.

JSONP (JSON with Padding) is an unofficial cross-domain data exchange protocol that allows integration on the server side

< script >

The tag is returned to the client to achieve cross-domain access in the form of javascript callback.

Because of the same origin policy, we cannot use XMLHttpRequest to communicate with external servers, but

< script >

You can access external resources, so you can communicate with the

< script >

In combination, the executable JavaScript function can be obtained directly from the external server by bypassing the same origin policy.

Principle

The client defines a function, such as jsonpCallback, and then creates

< script >

Src is in the form of url +? jsonp=jsonpCallback, and then the server generates a parameter with the same name as the passed jsonpCallback, and passes the data as a parameter, such as jsonpCallback (json), and returns it to the client. At this time, the client executes the jsonpCallback (json) callback returned by the server.

In popular terms, the client defines a function and then requests it. The javascript content returned by the server calls this function, and the required data is passed into the function as parameters.

Advantages-good compatibility, easy to use, support two-way communication between browser and server

Disadvantages-only GET requests are supported; there are security issues such as script injection and cross-site request forgery

In addition, JSONP does not use XMLHttpRequest objects to load resources and does not belong to AJAX in the real sense.

Fifteen. What's the difference between = and =?

The popular saying is that = is more stringent than =, and there is no type conversion in the comparison process.

What is a ternary expression (Ternary expression)? what does "Ternary" mean?

A ternary operator such as a name requires three operands.

The grammar is

Terms? Result 1: result 2

Here you write the conditions in the question mark (?) Is followed by result 1 and result 2 separated by a colon (:). If the condition is satisfied, result 1 is otherwise result 2.

What do you think of AMD vs. CommonJS?

Modular programming specification for browser-side async and server-side synchronization

Please name a typical use case of an anonymous function.

Define the callback function and execute it immediately as the function that returns the value, using the function defined by the method var foo = function () {}.

Describe the difference between the following variables: null,undefined or undeclared? How to detect them?

Undefined attributes, defined unassigned undefined,JavaScript access will not report an error; null is a special object;NaN is a special number;undeclared is an undeclared and unassigned variable, JavaScript access will report an error.

When will you use [xss_clean] ()?

The DOM method, which writes HTML expressions or JavaScript code to the document.

21. How to implement the following code: [1 recorder 2 3 4 5] .illustricator (); / / [1 2 3 4 4); / / [1 2 3 4 4 5]

Array.prototype.duplicator = function () {var l = this.length,i; for

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report