2017 front-End Questions JS Chapter (1)

Source: Internet
Author: User

1.请解释事件代理 (event delegation)

When you need to add events to many elements, you can trigger a handler function by adding events to their parent node through the delegate. It takes advantage of the browser's event bubbling mechanism.

var delegate = function(client, clientMethod) {  return function() {      return clientMethod.apply(client, arguments);  }}var agentMethod = delegate (client, clientMethod);agentMethod();// 获取父节点,并为它添加一个click事件document.getElementById("parent-list").addEventListener("click",function(e) {  // 检查事件源e.targe是否为Li  if(e.target && e.target.nodeName.toUpperCase == "LI") {    // 真正的处理过程在这里    console.log("List item ",e.target.id.replace("post-")," was clicked!");  }});

2.谈谈浏览器的事件冒泡机制

For the event capture and processing, different browser vendors have different processing mechanisms, we use the DOM2.0 definition of standard events as an example
The DOM2.0 model divides the event processing process into three stages: first, the event capture phase, the event target phase, and the event bubbling stage.

    • Event capture: When an element triggers an event (such as an onclick), the top-level object document emits an event stream as the DOM tree's node flows to the target element node until it reaches the target element that the event actually occurs. In this process, the corresponding listener function of the event is not triggered.

    • Event target: When the target element is reached, the corresponding handler function is executed for the event of the target element. If the listener function is not bound, it is not executed.

    • Event bubbling: Starts at the target element and propagates toward the top level element. On the way, if a node is bound to a corresponding event handler, these functions are triggered at once. If you want to block event blistering, you can use E.stoppropagation () (Firefox) or e.cancelbubble=true (IE) to organize the bubbling propagation of events.

3.JavaScript 中 this 是如何工作的。

    • As a function call, this binds the global object, and the browser Environment Global object is window.
    • The This of the intrinsic function is also bound to the global object, which should be bound to the object corresponding to its outer function, which is a bug of JavaScript, replaced with that.
    • Used as a constructor, this binds to the newly created object.
    • Used as an object method, this binds to the object.
    • Calling this with apply or call will be explicitly set to the first parameter of a function call.

4.谈谈CommonJs 、AMD 和CMD

COMMONJS specification, a single file is a module. Each module is a separate scope COMMONJS use representative: NodeJS

AMD the Asynchronous Module definition asynchronous module defines it as a specification for modular development in the browser-side AMD is a normalized output of the module defined by REQUIREJS during the promotion process

The CMD is the common module definition generic block that defines its representation as Seajs

Requirejs mainly solves two problems

    • Multiple JS files may have dependencies, the dependent files need to be loaded into the browser earlier than the files that depend on it
    • JS load when the browser will stop the page rendering, loading more files, the page lost response time longer

The difference between CMD and AMD

    • AMD is highly dependent on the pre-set and declares its dependent modules when defining the module
    • CMD respected the nearest dependency, only when using a module to go to require

5.谈谈对IIFE的理解

Iife-immediately-invoked function expression executes immediately

Not recommended

(function(){})();

Recommended

(function(){}());

In JavaScript, parentheses cannot contain statements, and when the parser interprets the code, it Encounters (), and then the Function keyword automatically recognizes the code in the () as a functional expression rather than a function declaration.

Knowledge Development:

function(){ /* code */ }();  解释下该代码能正确执行吗?

No, when the JavaScript code is interpreted, when the function keyword is encountered, it is assumed to be a function declaration, not a function expression, if it is not apparent to the surface of the function expression, it is an error, because the function declaration requires a function name, In the above code, the function does not have a function name. (The above code is also exactly in the execution to the first opening parenthesis (The Times is wrong, because (before theoretically there should be a function name.) )

function foo(){ /* code */ }();  解释下该代码能正确执行吗?

Parentheses are followed by an expression to indicate that the expression executes immediately, and if a statement is followed by parentheses, the parentheses do not match the previous statement, but only a grouping operator, which controls the precedence in the operation (the first operation in parentheses) is the equivalent of declaring a function called Foo, followed by ( ), but the expression within () (the grouping operator) cannot be empty, so an error is expressed. (The above code, that is, executed to the closing parenthesis, found that the expression is empty, so an error).

6..call 和 .apply 的区别是什么?

Foo.call (this, arg1,arg2,arg3) = = Foo.apply (this, arguments) ==this.foo (arg1, arg2, Arg3)

Call, apply method The difference is that, from the second parameter, called method parameters will be passed to the borrowed method as parameters, and apply directly put these parameters in an array and then passed, and finally the parameter list of the Borrowing method is the same.

7.请解释 Function.prototype.bind?

The main function of the bind () method is to bind a function to an object, and the bind () method creates a function in which the value of the This object is bound to the value of the incoming bind () function.

Principle

Function.prototype.bind = function(context) { var self = this; // 保存原函数 return function() { // 返回一个新函数  return self.apply(context, arguments); // 执行新函数时,将传入的上下文context作为新函数的this }}

Usage:

var paint = { color: "red", count: 0, updateCount: function() {  this.count++;  console.log(this.count); }};// 事件处理函数绑定的错误方法:document.querySelector(‘button‘) .addEventListener(‘click‘, paint.updateCount); // paint.updateCount函数的this指向变成了该DOM对象// 事件处理函数绑定的正确方法:document.querySelector(‘button‘) .addEventListener(‘click‘, paint.updateCount.bind(paint)); // paint.updateCount函数的this指向变成了paint

8.请解释原型继承 (prototypal inheritance) 的原理。

When a property is found for an object, JavaScript traverses the prototype chain up until it finds a property of the given name. --from the JavaScript Secret Garden

Each object in JavaScript has a built-in Proto property. This property is invisible to programming (although the ES6 standard opens this property, but the browser supports the visibility of the property differently), it is actually a reference to another object or null.

When an object needs to refer to a property, the JavaScript engine first looks for the property identifier from the property sheet of the object itself, and if found, reads and writes it, and if it is not found in its own property sheet, it is looked up in the property sheet of the object referenced by the Proto property. This happens until the property is found or the Proto property points to null.

The following code shows how the JS engine looks for properties:

//__proto__ 是一个不应在你代码中出现的非正规的用法,这里仅仅用它来解释JavaScript原型继承的工作原理。function getProperty(obj, prop) {if (obj.hasOwnProperty(prop))    return obj[prop]else if (obj.__proto__ !== null)    return getProperty(obj.__proto__, prop)else    return undefined}

JS's ECMA specification only allows us to use the new operator for prototype inheritance

Prototype inheritance

function Point(x, y) {this.x = x;this.y = y;}Point.prototype = {    print: function () { console.log(this.x, this.y); }};var p = new Point(10, 20);p.print(); // 10 20

By the way, how does the new operator work?

    • creates an instance of the class . This step is to set the Proto property of an empty object to F.prototype.
    • Initializes an instance of it. The function F is passed into the parameter and called, and the keyword this is set to that instance.
    • returns an instance .
function New (f) {    var n = { ‘__proto__‘: f.prototype }; /*第一步*/    return function () {        f.apply(n, arguments);            /*第二步*/        return n;                         /*第三步*/    };}

True prototype inheritance in JavaScript

Object.create = function (parent) {    function F() {}    F.prototype = parent;    return new F();};

Using true prototype inheritance, such as Object.create and Proto, has the following drawbacks:

    • Poor standard:Proto is not a standard usage, even a deprecated usage. At the same time, the original ecological Object.create and the original written by the Lord are different.
    • Poor optimization: Whether it is a native or a custom object.create, its performance is far from the optimization of new, the former is 10 times times slower than the latter.

ES6 internal implementation of class and class inheritance

class Parent {    constructor(name) { //构造函数          this.name = name;    }    say() {          console.log("Hello, " + this.name + "!");    }}class Children extends Parent {    constructor(name) { //构造函数        super(name);    //调用父类构造函数        // ...    }    say() {          console.log("Hello, " + this.name + "! hoo~~");    }}

Reference:

    • http://blog.csdn.net/xujie_0311/article/details/44466573
    • Http://blog.vjeux.com/2011/javascript/how-prototypal-inheritance-really-works.html

9.请尽可能详尽的解释 AJAX 的工作原理

The principle of Ajax is simply to send an asynchronous request to the server via the XMLHttpRequest object, get the data from the server, and then use JavaScript to manipulate the DOM and update the page. One of the most critical steps is getting the request data from the server.

How Ajax works without using


How to browse Web pages without using Ajax

How to work with Ajax


The principle of using AJAX Web pages

10.javascript中"attribute" 和 "property" 的区别是什么?

Property and attribute are very easy to confuse, and the Chinese translation of two words is very similar (properties: attributes, Attribute: properties), but in fact, they are different things and belong to different categories. Each DOM object will have its default basic properties, and when created, it will only create these basic properties, and the properties we customize in the tag tag are not placed directly in the DOM.

    • property is an attribute in the DOM and is the object in JavaScript;
    • attribute is an attribute on an HTML tag, and its value can only be a string;
    • The DOM has its default basic properties, which are called "property", which, in any case, will be created on the DOM object at initialization time.
    • If these properties are assigned at tag, then these values are assigned to the DOM's property with the same name as the initial value.


3 Friends of old Cold
Links: http://www.jianshu.com/p/8e505fe77762
Source: Pinterest
Copyright belongs to the author. Commercial reprint please contact the author for authorization, non-commercial reprint please specify the source.

2017 front-End Questions JS Chapter (1)

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.