Home > Web Front-end > JS Tutorial > body text

Summary of common JavaScrip interview questions and answers

不言
Release: 2018-12-11 09:58:48
forward
2116 people have browsed it

This article brings you a summary of common interview questions and answers about JavaScript. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

1. Please explain how this works in JavaScript.

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

1. Method calling mode

When a function is saved as an attribute of an object, it becomes a 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
Copy after login

2. Function calling mode

When the function is not an attribute of the object. The value of this in the function is the global object
note: the value of this in the internal function in a method is also the global object, not this of the external function

function foo(){
    this.name = 'fooname';  
}
foo();  // this => window
Copy after login

3. Constructor calling mode

That is, if the function is called using new, this will be bound to the newly constructed object.

function Foo(){
    this.name = 'fooname';
}
var foo = new Foo();  // this => foo
Copy after login

4. Use apply or call calling mode

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

function getName(name){
    this.name = name;
}
var foo = {};
getName.call(foo, name);  // this =>foo
Copy after login

The main method to change the value of this (currently thought of, comments are welcome to add):
Forcibly modify when the apply or call method is called, so that this points to the first parameter.
Use the Function.bind method to create a new function. This in the new function points to the first parameter provided.

2. Please explain the principle of prototypal inheritance.

JavaScript does not have the concepts of "subclass" and "parent class", nor the distinction between "class" and "instance". It all relies on the "prototype chain" mode. to implement inheritance.

Each function Sub has an attribute prototype. The prototype points to a prototype object. The prototype object also has an attribute constructor that points to the function. Through new, a function Sub can generate an instance instance and call a certain attribute of this instance. or method, the instance will first check whether it has this method or attribute. If not, it will search in the prototype prototype of the instance's constructor Sub, that is, Sub.prototype. If the prototype object Sub.prototype is assigned an instance of another type superInstance is searched in superInstance. There is also an attribute prototype in this superInstance that points to a certain prototype object. From this level up, it finally reaches Object.prototype, thus forming prototype inheritance.

Use this principle to implement an inherits function yourself:

function inherits(subType, superType){
    var _prototype = Object.create(superType.prototype);
    _prototype.constructor = subType;
    subType.prototype = _prototype;
}
Copy after login

3. Explain why the following code is not an IIFE (immediately called function expression): function foo(){ }( ); What changes need to be made to make it an IIFE?

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

Some functions of IIFE:

  1. Create a scope and store a large number of temporary variable codes internally to prevent naming conflicts.

  2. The outer layer of some libraries is wrapped in this form to prevent scope pollution.

  3. Run some code that is executed only once.

4. (function fn(){..})(), the function is included in a bracket and becomes an expression, followed by a (), it immediately Execute this function.

Some functions of IIFE:

  1. Create a scope and store a large number of temporary variable codes internally to prevent naming conflicts.

  2. The outer layer of some libraries is wrapped in this form to prevent scope pollution.

  3. Run some code that is executed only once.

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

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

Why:

1. Anonymous self-executing function

In some scenarios, the function only needs to be executed once, such as init() For functions like this, whose internal variables do not need to be maintained, we can use closures. We created an anonymous function and executed it immediately. Since its internal variables cannot be referenced from the outside, the resources will be released immediately after the function is executed without polluting the global object.

2. Encapsulation

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

5. What is the difference between .call and .apply?

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

The difference is that the second parameter is different. The second parameter of apply() is an array-like object arguments, and the parameters are all passed in in the form of an array, while call() passes a series of parameters to it. For example

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

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

6. Please explain Function.prototype.bind?

Function.prototype.bind方法会创建一个新函数,当这个新函数被调用时,它的this值是传递给bind()的第一个参数, 它的参数是bind()的其他参数和其原本的参数.
Copy after login

七、请指出 JavaScript 宿主对象 (host objects) 和原生对象 (native objects) 的区别?

宿主对象是指DOM和BOM。
原生对象是Object、Function、Array、String、Boolean、Number、Date、RegExp、Error、Math等对象。

八、请指出以下代码的区别:function Person(){}、var person = Person()、var person = new Person()?

function Person(){}
Copy after login

声明一个函数Person()。

var person = Person()
Copy after login

将函数Person()的结果返回给变量person,如果没有返回值则person为undefined。

var person = new Person()
Copy after login

new一个Person的实例对象。

九、请尽可能详尽的解释 Ajax 的工作原理。以及使用 Ajax 都有哪些优劣?

Ajax是无需刷新页面就能从服务器取得数据的一种方法。

Ajax通过XmlHttpRequest对象来向服务器发异步请求,从服务器获得数据,然后用javascript来操作DOM更新页面。

过程

  1. 创建XMLHttpRequest对象。

  2. 设置响应HTTP请求的回调函数。

  3. 创建一个HTTP请求,指定相应的请求方法、url等。

  4. 发送HTTP请求。

  5. 获取服务器端返回的数据。

  6. 使用JavaScript操作DOM更新页面。

缺点

  1. 对搜索引擎不友好

  2. 要实现Ajax下的前后退功能成本较大

  3. 跨域问题限制

十、请解释变量声明提升 (hoisting)。

变量的声明前置就是把变量的声明提升到当前作用域的最前面。
函数的声明前置就是把整个函数提升到当前作用域的最前面(位于前置的变量声明后面)。

//变量的声明前置
console.log(num);//undefined
var num = 1;

等价于

//变量的声明前置
var num;
console.log(num);//undefined
num = 1;
Copy after login

十一、请描述事件冒泡机制 (event bubbling)。

事件冒泡(event bubbling),事件最开始时由触发的那个元素身上发生,然后沿着DOM树向上传播,直到document对象。如果想阻止事件起泡,可以使用e.stopPropagation()。

十二、什么是 “use strict”; ? 使用它的好处和坏处分别是什么?

优点

消除Javascript语法的一些不严谨之处,减少一些怪异行为;
消除代码运行的一些不安全之处,保证代码运行的安全;
提高编译器效率,增加运行速度;
为未来新版本的Javascript做好铺垫。

缺点

严格模式改变了语义。依赖这些改变可能会导致没有实现严格模式的浏览器中出现问题或者错误。

十三、请解释 JavaScript 的同源策略 (same-origin policy)。

同源策略限制了一个源(origin)中加载文本或脚本与来自其它源(origin)中资源的交互方式。同源指的是协议、域名、端口相同,同源策略是一种安全协议。

十四、请解释 JSONP 的工作原理,以及它为什么不是真正的 Ajax。

JSONP(JSON with Padding)是一种非官方跨域数据交互协议,它允许在服务器端集成< script >标签返回至客户端,通过javascript回调的形式实现跨域访问。

因为同源策略的原因,我们不能使用XMLHttpRequest与外部服务器进行通信,但是< script >可以访问外部资源,所以通过JSON与< script >相结合的办法,可以绕过同源策略从外部服务器直接取得可执行的JavaScript函数。

原理

客户端定义一个函数,比如jsonpCallback,然后创建< script >,src为url + ?jsonp=jsonpCallback这样的形式,之后服务器会生成一个和传递过来jsonpCallback一样名字的参数,并把需要传递的数据当做参数传入,比如jsonpCallback(json),然后返回给客户端,此时客户端就执行了这个服务器端返回的jsonpCallback(json)回调。

通俗的说,就是客户端定义一个函数然后请求,服务器端返回的javascript内容就是调用这个函数,需要的数据都当做参数传入这个函数了。

优点 - 兼容性好,简单易用,支持浏览器与服务器双向通信
缺点 - 只支持GET请求;存在脚本注入以及跨站请求伪造等安全问题

补充一点,JSONP不使用XMLHttpRequest对象加载资源,不属于真正意义上的AJAX。

十五、== 和 === 有什么不同?

通俗的说就是===比==要更为严格,===比较过程中没有任何的类型转换。

十六、什么是三元表达式 (Ternary expression)?“三元 (Ternary)” 表示什么意思?

如名字表示的三元运算符需要三个操作数。
语法是
条件 ? 结果1 : 结果2;
这里你把条件写在问号(?)的前面后面跟着用冒号(:)分隔的结果1和结果2。满足条件时结果1否则结果2。

十七、你怎么看 AMD vs. CommonJS?

浏览器端异步和服务器端同步的模块化编程规范

十八、请举出一个匿名函数的典型用例?

定义回调函数,立即执行函数,作为返回值的函数,使用方法var foo = function() {}定义的函数。

十九、描述以下变量的区别:null,undefined 或 undeclared?该如何检测它们?

未定义的属性、定义未赋值的为undefined,JavaScript访问不会报错;null是一种特殊的object;NaN是一种特殊的number;undeclared 是未声明也未赋值的变量,JavaScript访问会报错。

二十、在什么时候你会使用 document.write()?

DOM方法,可向文档写入 HTML 表达式或 JavaScript 代码。

二十一、如何实现下列代码:[1,2,3,4,5].duplicator(); // [1,2,3,4,5,1,2,3,4,5]

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

二十二、解释 function foo() {} 与 var foo = function() {} 用法的区别

函数声明的两种方法:

  1. var foo = function () {}

这种方式是声明了个变量,而这个变量是个方法,变量在js中是可以改变的。
也:将一个匿名函数赋值给了变量。

  1. function foo() {}

这种方式是声明了个方法,foo这个名字无法改变

二十三、请解释可变 (mutable) 和不变 (immutable) 对象的区别。

在 JavaScript 中,对象是引用类型的数据,其优点在于频繁的修改对象时都是在原对象的基础上修改,并不需要重新创建,这样可以有效的利用内存,不会造成内存空间的浪费,对象的这种特性可以称之为 Mutable,中文的字面意思是「可变」。

Immutable 从字面上翻译成中文是「不可变」。每次修改一个 Immutable 对象时都会创建一个新的不可变的对象,在新对象上操作并不会影响到原对象的数据。

二十四、使用 Promises 而非回调 (callbacks) 优缺点是什么?

Promise是异步编程的一种解决方案,比传统的解决方案——回调函数和事件——更合理和更强大。它由社区最早提出和实现,ES6将其写进了语言标准,统一了用法,原生提供了Promise对象。

所谓Promise,简单说就是一个容器,里面保存着某个未来才会结束的事件(通常是一个异步操作)的结果。从语法上说,Promise是一个对象,从它可以获取异步操作的消息。Promise提供统一的API,各种异步操作都可以用同样的方法进行处理。

有了Promise对象,就可以将异步操作以同步操作的流程表达出来,避免了层层嵌套的回调函数。此外,Promise对象提供统一的接口,使得控制异步操作更加容易。

Promise也有一些缺点。

首先,无法取消Promise,一旦新建它就会立即执行,无法中途取消。
其次,如果不设置回调函数,Promise内部抛出的错误,不会反应到外部。
第三,当处于Pending状态时,无法得知目前进展到哪一个阶段(刚刚开始还是即将完成)。

二十五、请解释同步 (synchronous) 和异步 (asynchronous) 函数的区别。

同步调用,在发起一个函数或方法调用时,没有得到结果之前,该调用就不返回,直到返回结果;

异步调用的概念和同步相对,在一个异步调用发起后,被调用者立即返回给调用者,但调用者不能立刻得到结果,被调用者在实际处理这个调用的请求完成后,通过状态、通知或回调等方式来通知调用者请求处理的结果。

简单地说,同步就是发出一个请求后什么事都不做,一直等待请求返回后才会继续做事;异步就是发出请求后继续去做其他事,这个请求处理完成后会通知你,这时候就可以处理这个回应了。

二十六、你使用哪些工具和技术来调试 JavaScript 代码?

1.javascript的debugger语句
需要调试js的时候,我们可以给需要调试的地方通过debugger打断点,代码执行到断点就会暂定,这时候通过单步调试等方式就可以调试js代码

if (waldo) {
    debugger;
}
Copy after login

这时候打开console面板,就可以调试了

2.DOM断点
DOM断点是一个Firebug和chrome DevTools提供的功能,当js需要操作打了断点的DOM时,会自动暂停,类似debugger调试。
使用DOM断点步骤:
选择你要打断点的DOM节点
右键选择Break on..
选择断点类型

另外的调试方法例如alert, console.log,查看元素等就不再赘述了。

二十七、你会使用怎样的语言结构来遍历对象属性 (object properties) 和数组内容?

for in 语句
一般for循环
数组forEach方法

The above is the detailed content of Summary of common JavaScrip interview questions and answers. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:segmentfault.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!