JS Interview questions

Source: Internet
Author: User
Tags prototype definition variable scope

Write a random, object-oriented: (The above content is transcribed from object-oriented)
1. Object-oriented language has a flag, that is, the concept of owning a class, abstract instance object public properties and methods, based on the class can create any number of instance objects, generally with encapsulation, inheritance, polymorphism characteristics! But the object in JS is different from the object in pure object-oriented language, the ECMA standard defines the object in JS: A collection of unordered attributes, whose properties can contain basic values, objects, or functions.      The object that can be easily understood as JS is a set of unordered values in which the property or method has a name that can access the mapped value (the value can be the base value/object/method) 2. Prototype mode, like class mode, is a programming generic, which is the methodology of programming. In addition, the recently rounds function programming is also a programming generic. JavaScript's father Brendan Eich, when designing JavaScript, did not intend to add classes to the concept from the outset, but instead borrowed two other prototype-based languages: Self and Smalltalk. Since the object-oriented language is the same, there is a way to create objects. In a class language, an object is created based on a template, first defining a class as an abstraction of the real world, and then instantiating the object by the class, whereas in the prototype language, the object is created as a clone of another object, and the cloned parent is called the prototype object.    3. There are two types of objects: One is Object-based var person = new Object ();    Person.name = ' My name ';    Person.age = 18;    Person.getname = function () {return this.name;  }4. The other is the object literal form (a relatively clear Lookup object contains properties and methods) var person = {Name: ' My name ', age:18, getname:function        () {return this.name; }} can use "."    The operator dynamically expands and deletes person.newatt= ' new Attr ';//Add Attribute alert (Person.newatt);//new Attr Delete person.age;  alert (person.age);//undefined (the value is undefined after deleting the attribute); 5. object property types (divided into two categories) a) data properties-data genusSex refers to a location that contains a data value that can be read or written to a value that has 4 attributes for its behavior:-[[[Configurable]]: Indicates whether the delete operator can be removed to redefine it, or whether it can be modified as an accessor property.        The default is true; -[[[Enumberable]]: Indicates whether the property can be returned through the for-in loop.        Default true; -[[[Writable]]: Indicates whether the value of the property can be modified.        Default true; -[[Value]]: Contains the data value of the property. Read/write is the value. The default is undefined; if the name attribute is defined in the instance object person above, its value is ' My name ', the value is modified anyway at this location 6, to modify the default characteristics of the object properties (default is True),    You can call the Object.defineproperty () method, which receives three parameters: the object in which the property resides, the property name and a descriptor object (must be: Configurable, enumberable, writable, and value, one or more values can be set).        as follows: (Browser support: ie9+, Firefox 4+, Chrome, safari5+) var person = {}; Object.defineproperty (person, ' name ', {configurable:false, writable:false, value: ' Jac        K '});        alert (person.name);//jack delete person.name;        Person.name = ' Lily '; alert (person.name);//jack7, as you can see, The value of delete and reset person.name is not in effect, because calling the DefineProperty function modifies the properties of the object; It is worth noting that once the configurable is set to False, you can no longer use DefineProperty to modify it to true (Execution will be error: can ' t redefine non-configurable property); * * For data properties, get: configurable,enumberable, writable and value;** b) accessor properties-it primarily consists of a pair of getter and setter functions that, when read accessor properties, invoke the getter to return a valid value, and when the accessor property is written, the setter is called, and the new value is written, and the property has the following 4 characteristics :-[[[[Configurable]]: Whether the redefined property can be deleted through the delete operator;-[[Numberable]]: Whether the property can be found through the for-in loop;-[[[Get]]: Called when the property is read, the default        Recognition: undefined;        -[[Set]]: Called when writing properties, default: undefined;            -accessor properties cannot be defined directly and must be defined using DefineProperty (), as follows: var person = {_age:18};                    Object.defineproperty (person, ' isadult ', {get:function () {if (this._age >= 18) {                    return true;                    } else {return false;            }                }            }); Alert (person.isadult? ') Adult ': ' minor ');//adult-from above, the getter and setter functions are not required to define the accessor properties, and the configurable and writable attributes of the property cannot be specified when getter and setter are defined;            , ECMA-262 (5) also provides a object.defineproperties () method that can be used to define properties of multiple properties at once: var person = {}; Object.defineproperties (person,{_age:{value:19}, isadult:{get:function () {                        if (This._age >=) {return true;                        } else {return false;            }                    }                }            });  * * For accessor properties, you can get: Configurable,enumberable,get and Set**6. Creating objects (using object constructors or object literals can create objects, but the disadvantage is that when you create multiple objects, there is a lot of duplicate code, so here's how to create an object that solves the problem) a) Factory mode function Createperson (name            , age, Job) {var o = new Object ();            O.name = name;            O.age = age;            O.job = job;            O.getname = function () {return this.name;        Return o;//Returns the generated object instance using return} var person = Createperson (' Jack ', ' software Engineer '); * * The creation of objects is given to a factory method, which can pass parameters, but the main disadvantage is that object types cannot be recognized because the objects are created using the native constructor of object. * * b) constructor mode function person (name,age,job) {thIs.name = name;            This.age = age;            This.job = job;            This.getname = function () {return this.name;        }} var person1 = new Person (' Jack ', ' n ', ' software Engineer ');        var = new person (' Liye ', Person2, ' mechanical Engineer '); Define the properties and methods of the object type (for example, person) by using a custom constructor (just like a normal function, which is used only to create objects). It differs from the factory method in that it does not explicitly create an object that assigns properties and methods to the This object, no return statement, and, in addition, to create an instance of the person, you must use the new keyword to P The Erson function is a constructor, passing parameters to complete the creation of the object; the actual creation passes through the following 4 procedures: Creating an object assigns the scope of the function to the new object (so this is the new object, such as: person1) execution constructor The code returns the object above the two objects generated by the person constructor Person1 and Person2 are all instances of person, so you can use instanceof to judge, and because all objects inherit object, so                Person1 Instanceof Object also returns true: Alert (person1 instanceof person);//true;                Alert (person2 instanceof person);//true;                Alert (Person1 instanceof Object);//true;   Alert (Person1.constructor = = = Person2.constructor);//ture;     Although the constructor is quite good, there are drawbacks, that is, when creating an object, specifically for the object's properties point to the function, will be repeatedly created function instances, based on the above code, can be rewritten as: function person (name,age,job) {                THIS.name = name;                This.age = age;                This.job = job;                This.getname = new Function () {//rewrite the effect is the same as the original code, but to facilitate the understanding of return this.name;    }} The code above, when creating multiple instances, calls the new function () repeatedly, creating multiple instances of the functions that are not in a scope, and of course, this is not an error, but it can cause memory waste. Of course, a reference to GetName = GetName can be defined in the function, and the GetName function is defined outside the person, which resolves the problem of repeating the creation of the function instance, but the effect does not encapsulate the effect as follows: function Pers                On (name,age,job) {this.name = name;                This.age = age;                This.job = job;            This.getname = GetName;                } function GetName () {//Everywhere is code, look at the mess!!            return this.name; } c) prototype mode (JS each function has a prototype (prototype) attribute, which is a pointer to an object, which is the prototype object for all instances created with the function using the new operator. The most important feature of a prototype object is that all object instances share the properties and methods it contains, that is, all properties or methods created in the prototype object are shared directly by all object instances.               ) function person () {} Person.prototype.name = ' Jack ';//use prototype to add attribute Person.prototype.age = 29;        Person.prototype.getName = function () {return this.name;        } var person1 = new Person ();        Alert (Person1.getname ());//jack var person2 = new Person (); Alert (Person1.getname = = = Person2.getname);//true; The method prototype that shares a prototype object is pointed to the prototype object, which is not much related to the constructor. The only relationship is that the prototype of the function is pointing to this prototype object!        An object instance created based on a constructor also contains an internal pointer to: [[prototype]] pointing to the prototype object. The access procedure for an instance property or method is a search process:-Start with the object instance itself, return the property value directly if the attribute is found, or, if the instance itself does not exist to find the attribute, continue to search for the prototype object pointed to by the pointer, in which to find the property of the given name, if any to return;-based on the above analysis, the prototype model creates an object instance whose properties are shared with the prototype object, but can also be defined in its own instance, and is not obtained from the prototype object when it is found, but rather the return of this instance is based on the search principle, which simply means that the attribute in the instance    Masks the properties in the prototype object; The prototype and in operators in a word: Regardless of the properties in the prototype, or the properties of the object instance, can be accessed using the In operator, to determine whether the property of the instance itself can be judged by using Object.hasownproperty (' attr '); Prototypes in native objects are like prototypes of ordinary objects, you can add/modify properties or methods, such as the following code to add left and right blank prototypes for all string objects: String.prototype.trim = Functio N () {RetuRN This.replace (/^\s+/, "). Replace (/\s+$/,");            } var str = ' word space '; Alert ('! ') +str.trim () + '! ');        /!word space! The disadvantage of prototype mode is that it omits to pass the initialization parameters for the constructor, which is inconvenient in certain procedure, and the most important thing is that when the object's property is a reference type, its value is constant, always referencing the same external object, all instances of the operation of the object will be other instances: function Per            Son () {} Person.prototype.name = ' Jack ';            Person.prototype.lessons = [' Math ', ' Physics '];            var person1 = new Person ();            Person1.lessons.push (' biology ');            var person2 = new Person (); alert (person2.lessons);//math,physics,biology,person1 modification affects person2 D) combinatorial constructors and prototype patterns (currently the most commonly used definition type mode is the combination constructor pattern and prototype pattern. The constructor pattern is used to define the properties of the instance, whereas the prototype pattern is used to define methods and shared properties. As a result, each instance will have its own copy of the instance properties, but at the same time share a reference to the other method, maximizing memory savings.            In addition, the combination mode supports passing parameters to the constructor, which is the director of the two family.                function person (name, age, Job) {this.name = name;                This.age = age;                This.job = job;            This.lessons = [' Math ', ' Physics ']; } Person.prototype = {cThe onstructor:person,//prototype literal method converts the object's constructor into object, and also forces the person getname:function () {                return this.name;            }} var person1 = new Person (' Jack ', ' n ', ' software engneer ');            Person1.lessons.push (' biology ');            var = new person (' Lily ', Person2, ' mechanical engneer '); alert (person1.lessons);//math,physics,biology alert (person2.lessons);//math,physics Alert (person1.ge                Tname = = = Person2.getname);//true,//shared prototype definition method in the Contact JS Library, jquery type encapsulation is the use of combination mode to instance!!! e) Dynamic prototype mode (the instance attribute in the combined mode is separated from the shared method (defined by the prototype), which is not quite consistent with the pure object-oriented language, and the dynamic prototype pattern encapsulates all the construction information in the constructor and preserves the advantages of the combination. The principle is to determine whether a shared method or property has been defined in the prototype of the constructor, and if not, the definition process is no longer performed. The method is only defined once on the prototype, and all construction procedures are encapsulated in the constructor, and modifications to the prototype are immediately reflected in all instances: function person (name, age, job) {T                His.name = name;                This.age = age;                This.job = job;            This.lessons = [' Math ', ' Physics '];           } if (typeof this.getname! = ' function ') {//By judging instance encapsulation Person.prototype = {Constructor:pe The rson,//prototype literal method converts the object's constructor into object, and also forces the person getname:function () {return th                   Is.name;            }}} var person1 = new Person (' Jack ', ' n ', ' software engneer ');            Person1.lessons.push (' biology ');            var = new person (' Lily ', Person2, ' mechanical engneer '); alert (person1.lessons);//math,physics,biology alert (person2.lessons);//math,physics Alert (person1.ge Tname = = = person2.getname);//true,//definition method in shared prototypes
Second, the prototype
        function person (name) {this.name=name;               This.showme=function () {alert (this.name);        }} var one = new Preson (' JavaScript ');            Alert (One.showme ()); The person defined by the function is an object, and it is a very special object, and there is an important difference between an object that uses a function definition and an object that is generated by using the new operator.    The difference is that the function-defined object has a prototype property, and the object created with new does not have this prototype property, which we generally call ordinary objects! We need to understand the logical order of memory: Person is an object, it has a prototype prototype property (because all objects are prototype prototypes!). The prototype property has its own prototype object, and Pototype object certainly has its own Constuct property, construct property has its own constructor object, the magic thing to happen, this last            constructor objects are the function functions that we construct!            function person (name) {this.name=name;               This.showme=function () {alert (this.name);        }} var one = new Preson (' JS '); alert (one.prototype);//undefined proves that the new object is a non-prototype alert (TypeOf Person.prototype)//object that the type of prototype of the function we have constructed is           An Object! Alert (Person.prototype.constructor)//Returns the function itself, proves the theory of the prototype,

Practical use: It gives us the most practical use that we can use prototypes to create properties and methods of objects! We don't have to. It is also possible to create properties and methods! There is a difference here, since it is not the same there is the value of existence! We can add properties or methods to an object by adding properties and methods to the prototype!

Hero.prototype.name;Hero.prototype.sayMe = function(){"添加对象的方法其实就是添加函数"}让我们再深一步:当我们给对象添加了同名的属性或方法时会发生什么?        function Hero(){            this.name="zhangsan"            this.sayMe = function(){                alert("this is zhangsan.")            }           }        //通过原型增加的属性和方法        Hero.prototype.name1 = "wangwu";        Hero.prototype.sayMe1 = function(){            alert("this is wangwu.")        };        var hero = new Hero();        alert(hero.name)        alert(hero.name1)        hero.sayMe();        // delete hero.name        alert(hero.name)//

We have validated this example to get some conclusions:
When the property or method of the function object itself is the same as the property or method of the prototype:

1、默认调用的是函数对象本身的属性或方法.2、通过原型增加的属性或方法的确是存在的.3、函数对象本身的属性或方法的优先级要高于原型的属性或方法.      
Three, scope, prototype chain and the difference between the two

Scope is for variables, for example, we create a function that contains a function, and now there are three scopes

Global scope ==> function 1 Scope ==> function 2 scope

The scope is characterized by first finding it in its own variable range, and if not, it will look up along the scope.

Such as:

var a = 1;function b(){    var a = 2;    function c(){        var a = 3;        console.log(a);    }    c();}b();

The last print is 3, because when the function C () is executed, it finds the variable a in its own scope, so it will not continue to look up, if it is not found in function C () will continue to look up, always find the global variable A, this lookup process is called the scope chain.

I wonder if you have any doubts about why function C can look up variable A in function B, because function c is created in function B, that is, the scope of function C includes the scope of function B, and of course the global scope, but function B cannot find the variable in function C because the scope will only look up.

The prototype chain is for constructors, for example, if I create a function and then use a variable to new The function, then the new function inherits the property of the created function, and then if I access a property of this function from new, But I did not define this variable in the new function, and then it looked up (to the function that created it), and the process of finding it was called the prototype chain.

Object ==> Constructor 1 ==> Constructor 2

As with inheritance in CSS, the style of the parent element is inherited if it is not defined by itself.

function a(){};a.prototype.name = "abc";var b = new a();console.log(b.name); //abc
Four, closed package

The scope of a variable

To understand closures, you must first understand the special variable scope of JavaScript.

The scope of a variable is nothing more than two kinds: global variables and local variables.

The special point of the JavaScript language is that the global variables can be read directly inside the function.

    var n=999;    function f1(){        alert(n);    }       f1(); // 999

On the other hand, a local variable inside a function cannot be read naturally outside the function.

    function f1(){        n=999;    }    f1();    alert(n); // 999    

Second, how to read the local variables from the outside?
For a variety of reasons, we sometimes need to get local variables within the function. However, as already mentioned, under normal circumstances, this can not be done, only through the workaround to achieve.

That is, in the inside of the function, define a function.

function f1(){    var n=999;    function f2(){        alert(n); // 999    }}

In the above code, the function F2 is included inside the function F1, and all local variables inside the F1 are visible to the F2. But the opposite is not possible, F2 internal variables, the F1 is not visible. This is the JavaScript-specific "chain-scoped" structure (chain scope), where child objects look up the variables of all the parent objects one level at a level. Therefore, all the variables of the parent object are visible to the child object, and vice versa.

Since F2 can read the local variables in the F1, we can not read its internal variables outside the F1 as long as the F2 is the return value!
  

    function f1(){        var n=999;        function f2(){            alert(n);         }return f2;}    var result=f1();    result(); // 999

Three, the concept of closure

The F2 function in the previous section of the code is the closure.

The definition of "closure" (closure) in various professional literature is very abstract and difficult to read. My understanding is that closures are functions that can read other functions ' internal variables .

Because in the JavaScript language, only sub-functions inside the function can read local variables, it is possible to simply interpret the closure as "a function defined inside a function".

So, in essence, a closure is a bridge that connects the inside of the function to the outside of the function.

Iv. use of closures

Closures can be used in many places. Its maximum usefulness is two, one of the previously mentioned variables that can read the inside of a function, and the other is to keep the values of these variables in memory at all times.

How to understand this sentence? Take a look at the following code.

function f1(){    var n=999;    nAdd=function(){        n+=1    };    function f2(){        alert(n);    }return f2;}var result=f1();result(); // 999nAdd();result(); // 1000

In this code, result is actually the closure F2 function. It runs altogether two times, the first value is 999, the second value is 1000. This proves that the local variable n in the function F1 is kept in memory and is not automatically cleared after the F1 call.

Why is that? The reason is that F1 is the parent function of F2, and F2 is assigned to a global variable, which causes F2 to always be in memory, and F2 's presence depends on F1, so F1 is always in memory and will not be reclaimed by the garbage collection mechanism (garbage collection) after the call ends.

Another notable part of this code is the line "nadd=function () {n+=1}", which first did not use the var keyword in front of Nadd, so Nadd is a global variable, not a local variable. Second, the value of Nadd is an anonymous function (anonymous functions), and the anonymous function itself is a closure, so nadd is equivalent to a setter that can manipulate local variables inside the function outside of the function.

V. Note points for using closures

1) Because the closure will make the variables in the function are stored in memory, memory consumption is very large, so can not abuse closures, otherwise it will cause the performance of the Web page, in IE may cause memory leaks. The workaround is to remove all unused local variables before exiting the function.

2) The closure changes the value of the inner variable of the parent function outside the parent function. So, if you use the parent function as an object, and the closure as its public method, and the internal variable as its private property (private value), be careful not to arbitrarily change the value of the inner variable of the parent function.

Liu, study questions

If you can understand the results of the following two sections of code, you should understand the operation mechanism of the closure.

Code snippet one.

    var name = "The Window";    var object = {        name : "My Object",        getNameFunc : function(){            return function(){                return this.name;            };        }    };    alert(object.getNameFunc()());

Code snippet two.

    var name = "The Window";    var object = {        name : "My Object",        getNameFunc : function(){            var that = this;            return function(){                return that.name;            };        }    };    alert(object.getNameFunc()());
Five, the red Book inside the method and the development of the usual advantages and disadvantages of six, how do you develop modular

  JavaScript modular programming has become an urgent requirement. Ideally, developers only need to implement core business logic, and others can load modules that others have already written.

First, the original wording
A module is a set of methods for implementing a specific function.

Simply put the different functions (and the variables that record the state) together, even if it is a module.

    function m1(){        .....    }    function m2(){        .....    }

The above functions M1 () and M2 () to form a module. When used, call directly on the line.

The disadvantage of this approach is obvious: "Pollute" the global variable, there is no guarantee that the variable name conflicts with other modules, and the module members do not see a direct relationship.

Ii. the wording of the object

In order to solve the above shortcomings, the module can be written as an object, all the module members are placed in this object.

    var module1 = new Object({    _count : 0,    m1 : function (){      //...    },    m2 : function (){      //...    }  });

The above functions M1 () and M2 () are encapsulated in the Module1 object. When used, it is called the property of the object

    module1.m1();

However, such a notation exposes all module members, and the internal state can be overridden externally. For example, external code can directly change the value of an internal counter.

    module1._count = 5;

Iii. immediate execution of function notation

Using the Execute functions now (immediately-invoked function Expression,iife), you can achieve the purpose of not exposing private members.

    var module1 = (function(){    var _count = 0;    var m1 = function(){      //...    };    var m2 = function(){      //...    };    return {      m1 : m1,      m2 : m2    };  })();

Using the notation above, the external code cannot read the internal _count variable.

    console.info(module1._count); //undefined

Module1 is the basic way of writing JavaScript modules. The following, and then processing the writing.

Four, amplification mode

If a module is large and must be divided into several parts, or if one module needs to inherit another module, then it is necessary to use "magnification mode" (augmentation).

    var module1 = (function (mod){    mod.m3 = function () {      //...    };    return mod;  })(module1);

The code above adds a new method M3 () to the Module1 module and then returns the new Module1 module.

Five, wide magnification mode (Loose augmentation)

In a browser environment, parts of the module are usually obtained from the web, and sometimes it is not possible to know which part is loaded first. If you use the previous section, the first part of the execution is likely to load a nonexistent empty object, then use the "wide magnification mode".

    var module1 = ( function (mod){    //...    return mod;  })(window.module1 || {});

In contrast to Loupe mode, the wide magnification mode is a parameter that executes function immediately, which can be an empty object.

Details to walk you!!!

Vii. What is the difference between MVC and MVVM?

Mvc
The well-known MVC framework Rails MVC View layer and the model layer do not have direct coupling, but instead pass the information through the controller as a middleman:

    Model-View-Controller    View ==> Controller ==> Model ==> View


The view communicates instructions to the controller, the controller runs the business code, the feedback to the model changes state, and the model passes the data to the view for presentation.

当存在用户操作时有两种方式:    1、通过 View 接受指令,传递给 Controller。        用户 ==> View ==> Controller ==> Model ==> View


2, directly through the controller to accept the instructions.
User ==> Controller ==> Model ==> View

实际开发中会更加灵活的运用例如:    1、用户可以向 View 发送指令(DOM 事件),再由 View 直接要求 Model 改变状态。    2、 用户也可以直接向 Controller 发送指令(改变 URL 触发 hashChange 事件),再由 Controller 发送给 View。    3、 Controller 非常薄,只起到路由的作用,而 View 非常厚,业务逻辑都部署在 View。所以,Backbone 索性取消了 Controller,只保留一个 Router(路由器)


Mvp

    MVP 模式将 Controller 改名为 Presenter,同时改变了通信方向。    View ==> Presenter ==> Model    Model ==> Presenter ==> View    1、 各部分之间的通信,都是双向的。    2、View 与 Model 不发生联系,都通过 Presenter 传递。    3、View 非常薄,不部署任何业务逻辑,称为"被动视图"(Passive View),即没有任何主动性,而 Presenter非常厚,所有逻辑都部署在那里。


MVVM

MVVM 模式将 Presenter 改名为 ViewModel,基本上与 MVP 模式完全一致。       唯一的区别是,它采用双向绑定(data-binding):View的变动,自动反映在 ViewModel,反之亦然。Angular 和 Ember 都采用这种模式。

Viii. use of the arttemplate template engine

  principle: execute JavaScript strings dynamically!

  Advantages:

    1. 预编译:渲染需要动态编译JavaScript字符串完成变量赋值。而artTemplate的编译赋值过程却是在渲染之前完成的     2. 更快的字符串相加方式: IE6-8的浏览器下,数组push方法拼接字符串会比“+=”快,而在v8引擎中,使用“+=”方式比数组拼接快4.7倍;所以 artTemplate 根据JavaScript引擎特性采用了两种不同的字符串拼接方式。     3. 支持运行时调试,可精确定位异常模板所在语句:(动态解析,所以调试器无法定位到错误)渲染的时候遇到错误会进入调试模式重新编译模板,而不会影响正常的模板执行效率。模板编译器根据模板换行符记录行号,当执行过程遇到错误,立马抛出异常模板对应的行号,模板调试器再根据行号反查模板对应的语句并打印到控制台。源码L282     4. 对Node端支持良好,便于以后统一扩展!

JS Interview questions

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.