In this chapter in the function-oriented explanation, it will inevitably involve the contents of arrays and objects, it is not difficult to understand, the knowledge of the future involved in the content of the more natural.
(1) Classic scope issues
Title One:
var a = 0function f () { console.log (a); ==>undefined var a = 2; Console.log (a); ==>2}f ()
The second log output is relatively easy to understand, the key is that the first print result is not a global variable, because according to the scope chain of the lookup rule, when the function is executed to find the local scope, while the local scope already exists variable A, but has not been executed to the assignment stage, So the print result is undefined.
Question two:
var a = 0function f (a) { console.log (a); ==>1 var a = 2; Console.log (a); ==>2}f (1)
Compared to the first, there is more than one name parameter a, before the function body executes, A has been assigned to the value of the argument, so the print result is 1.
About the scope chain: When the function executes, the execution context object is generated internally, it contains two properties, one is the active object, one is the scope property, and the active object is filled with arguments, function body variables, this object, argument object at the beginning of the function body execution. The scope property points to the active object of the upper function, and when the variable lookup is performed in the function body, it is first found within the active object of the function, and if not, the global window object is looked up to, and so on, from the active object of the upper function that the scope points to.
(2) Pre-compilation period and execution period
var f = function () {console.log (1)}function f () {Console.log (2)}f () ==>1
It is not easy to assume that the JS code executes from top to bottom, so the next function definition overrides the previous function definition. In fact, JS before the implementation of a pre-compilation period, all through the Var declaration of variables and functions declared in the pre-compilation period of JS processing (including the variable name index and function function body to parse), When the function body inner statement and the associated logical resolution are parsed, it is stored in the address pointed to by the functional variable waiting for the function call. In the execution period of JS, F is re-assigned to change the reference address, while actually executing the function f () {Console.log (2)} This declarative statement will not be executed (during the precompilation process) or any other changes, so the final result is 1.
Study Questions
function test () { alert ("1"); } Test (); function test () { alert ("2");} Test ();
(3) The function determines the data type and returns
function GetType (obj) { return Object.prototype.toString.call (obj). Slice (8,-1);}
This method is more convenient than using Typeof/instance/constructor, and is currently the most used method. It takes advantage of the object's built-in objects prototype method to return the properties of various types of special strings, which can all be distinguished from 8 data types. But in fact the Object.prototype.toString method is not specifically designed to differentiate between data types, it returns a string type that is not only 8, and if necessary consider both of these special cases: the Arguments object returns ' Arguments ', The DOM object returns ' Htmldivelement '.
(4) Small test sledgehammer: function implementation to take the maximum value, the number of function parameters, such as fun (2,fun) return (1,2,3,4) return 4
Method One:
function Max () { var arr = [].slice.call (arguments,0); Arr.sort (function (A, b) {return-A-B ; }) return Arr.pop ();}
This paper examines the use and sequencing of arguments objects, and it is important to note that the arguments object needs to be converted to a real array before using the Sort method, where [] is used. Slice.call, equivalent to Array.prototype.slice.call, whose address references are the same. Of course, I believe the interviewer will be happier if you change the answer to the following question.
Method Two:
function Max () { return Math.max.apply (null,arguments);}
Of course, there is no parameter type to consider, if you want to consider some exceptions or, you can add these special processing.
(5) function, array, object comprehensive problem
The existing data objects are:
var students = [{name: ' Lilei ', Sex: ' Girl ', scores:{math:88,english:69}},......]
function function requirement (1):
Functional Requirements: Logs print out the array function getstudent (sex) {//todo) that holds the names of male or female students or all students
... console.log (arr);} Getstudent ();
Answer:
function getstudent (Sex) {var arr = [];//store final result for (I in students) {if (sex = = undefined) {Arr.push (students[i].name);} else if (students[i].sex = = Sex) {Arr.push (students[i].name);}} Console.log (arr);}
function function requirement (2):
Functional Requirements: Logs print out the array function Getscore (Subject) {//todo...console.log (arr) that holds all student scores for an account;} Print all student math scores//getscore (' math ');
Answer:
function Getscore (Subject) {var arr = [];//Store all scores for this account for (I in students) {Arr.push (Students[i].scores[subject]);} Console.log (arr);}
function function requirement (3):
Functional Requirements: Log prints An object that is the student name of the lowest or highest score for an account, the function getobj (subject,maxormin) {//todo ... Console.log (obj);} Print the student's name and math score with the highest score: {name:***,math:**}getobj (' 中文版 ', ' min ');
Answer:
function Getobj (subject,maxormin) {var obj = {};var Student;students.sort (function (A, b) {return A.scores[subject]- B.scores[subject]; Arrange by score from small to large}) if (maxormin = = ' Max ') {student = students[students.length-1];} Else{student = Students[0];} Obj.name = Student.name;obj[subject] = Student.scores[subject];}
(6) This application scenario in the function
Question one: this in the normal function
var a = 0;function fun () { var a = ' fun '; Console.log (THIS.A); ==>0}
This in the normal function points to the Window object
Question two: This in the method
var a = 0;var obj = { A: ' obj ', fun:function (a) { console.log (THIS.A); ==> ' obj ' }}obj.fun (1);
When a function is called as a method of an object (the object's property value is a function, which we call the method of the object), the this in the method points to the object that called the method.
Study Questions
var a = 0;var obj = { A: ' obj ', fun:function (a) { return function () { console.log (THIS.A); ==>? Try it yourself, Then think about why } }}obj.fun (1) ();
Title three: This in setTimeout and setinterval
var a = 0;var obj = { A: ' obj ', fun:function (a) { setTimeout (function () { console.log (THIS.A); ==>0 },1000) }}obj.fun (1);
In settimeout and setinterval this always points to window, so if you expect the output to be a property value of the Obj object in question three, you can modify this:
var a = 0;var obj = { A: ' obj ', fun:function () { var _this = this; SetTimeout (function () { console.log (_THIS.A); ==> ' obj ' },1000) }}obj.fun ();
Topic Four: Calling as a constructor function
var a = 0;function Obj () { THIS.A = 1;} var o = new Obj (); Console.log (O.A); ==>1
This is a simple constructor that, during the new operation, the instantiated object will override this point in the constructor, which is equivalent to Obj.call (o).
Question five: In the event handle of the dom element
<div onclick= "Fun" >ddd</div><script>function (EL) { console.log (EL); ==> The DOM object that triggered the event handle}</script>
(7) Object-oriented issues
Topic One: Implementing an inheritance
JS Pen Test Series three--function