Home >Web Front-end >JS Tutorial >Summary of important JS knowledge points_javascript skills

Summary of important JS knowledge points_javascript skills

WBOY
WBOYOriginal
2016-05-16 17:59:321053browse

The explanation is still in the form of sample code with comments. Here is a small directory:
JS code pre-parsing principle (including three paragraphs);
Function related (including function parameter transfer, calling method of function with parameters, closure package);
Object-oriented (including object creation, prototype chain, data type detection, inheritance).
JS code pre-parsing principle

Copy code The code is as follows:

/****************** Principle of JS code pre-parsing ********************/
/*
JS code pre-parsing, variable scope, scope chain, etc. should be used as introductory knowledge for learning the JS language.
A brief explanation and some typical code snippets are given below. If you want to know more, you can search for more related examples on the Internet.
Quoting an explanation from the Internet about "JS execution order":
If a document flow contains multiple script code segments (js code separated by script tags or introduced js files), their running order It is:
Step 1. Read the first code segment (the js execution engine does not execute the program line by line, but analyzes and executes it piece by piece)
Step 2. Do syntax analysis and report syntax errors if there are any. Error (such as mismatched brackets, etc.), and jump to step 5
Step 3. Do "pre-parsing" of var variable and function definitions (an error will never be reported, because only correct declarations are parsed)
Step 4. Execute the code segment and report an error if there is an error (for example, the variable is undefined)
Step 5. If there is another code segment, read the next code segment and repeat step 2
Step 6. End
*/
// Here are three code examples that I think are relatively typical:
/********** 1: Basic statements **********/
alert(num); // undefined
var num = 0;
alert(str); // Error: str is undefined
str = "string";
alert(func); // undefined
var func = function (){ alert('exec func '); }
test(); // exec test
alert(test()); // exec test first and then undefined
function test(){ alert('exec test'); }
/********** 2: The function name is the same as the variable name **********/
//var mark = 1;
function mark(x) {
return x * 2;
}
var mark;
alert(mark); // function mark(x) { return x * 2; }
// Remove the preceding var mark = 1; then 1 will be returned
/********** Three: Include the second paragraph in the statement block **********/
// When there is a condition (the code is contained in a conditional statement block)
if (false) {
var mark1 = 1;
function mark1() {
alert("exec mark1");
}
//var mark1;
alert(mark1);
}
alert(mark1);
mark1();
// Due to different parsing browsers , the results of executing this code in different browsers are inconsistent. The specific reasons can be found online.

Function related (including function parameter transfer, calling method of function with parameters, closure)
Copy code The code is as follows:

/****************** Function related **********************/
/********** 1: Function parameter transfer **********/
/*
Programming languages ​​generally have differences between value types and reference types, and JS is no exception .
Original types: undefined null number boolean are all value types.
String is special because it is immutable, and none of the methods defined by the String class can change the content of the string.
function object array These three types are reference types.
*/
/* When JavaScript functions pass parameters, they are passed by value.
In ECMAScript, all function parameters are passed by value.
The transfer of basic type values ​​is consistent with the copying of basic type variables (new values ​​are created on the stack),
The transfer of reference type values ​​is consistent with the copying of reference type variables (pointers are stored in the stack, pointing to the same value in the heap) object).
Specific reference: http://www.xiaoxiaozi.com/2010/03/05/1719/
*/
function setName(obj){
//obj copies the value of person ( person is the reference address of an object), so obj also points to the object pointed to by person.
obj.name = "xiaoxiaozi";
obj = {}; // Let obj point to another object
obj.name = "admin";
}
var person = { };
setName(person);
alert(person.name); // xiaoxiaozi
/********** 2: How to call functions with parameters **********/
/* In different versions of the DOM, the function calling method is different Same. The standard recommendations are addEventListener and attachEvent
There is a lot of information available for these two methods. However, some function calls that are no longer recommended still have practical applications, and not much relevant information has been found.
Here we mainly discuss these function calling methods
*/
var g = "global variable";
function show(str) {
alert("my site: " str);
}
setTimeout("show(g);",100); // g is a global variable and the function is executed correctly
function t() {
var url = "www.xujiwei.cn";
var num = 2;
//setTimeout("alert(" url ")", 3000); // Parsing error, www is undefined
//setTimeout("alert(" num ")" , 3000); // The parsing is correct, please compare with the previous sentence
//setTimeout("show('url');", 2000); // url
//setTimeout("show(" url " );", 2000); // Parsing error, www is not defined
//setTimeout("show(url);", 2000); // Parsing error, url is not defined
//setTimeout('" show(" url ");"', 2000); // Parsing error, url is undefined
//setTimeout("show('" url "');", 2000); // Correct
/ /setTimeout(function(){show(url);},1000); // Correct
}
t();
/* Conclusion:
Such as onclick="xx();" In other function calling methods, the content within double quotes is directly parsed into js statements for execution.
If the called function has parameters, pay attention to comparing the above various writing methods to ensure that the parameters passed in are correct.
*/
/********** Three: Closure **********/
/*
Closure is an issue that almost every friend who studies JS will discuss, so there are all kinds of related information.
It is very useful, but it also has disadvantages. For example, if used improperly, it can easily cause memory leaks and other problems. Therefore, many people
advocate using closures less.
Here is a classic application of closure, a controversial application.
*/
function test1() { //Through closure, different j values ​​can be passed in each time.
for (var j = 0; j < 3; j ) {
(function (j) {
setTimeout(function () { alert(j) }, 3000);
}) (j);
}
}
test1();
/* This is a typical application of closures*/
(function tt() {
for (var i = 1; i < 4; i ) {
document.getElementById("b" i).attachEvent("onclick",
new Function('alert("This is button' i '");') ); // Test in IE
}
})() // Execute the function immediately. Can there be only one per file? What's wrong with writing the above function to be executed immediately?
/* This question appeared in the forum, and there was a lot of controversy.
It is said that new Function dynamically generates a function with a closure structure, so it can save external variables.
It is said that it has nothing to do with closure. New Function is a newly defined function.
The value of i is also solidified inside it as a parameter of this new function.
*/

Object-oriented (including object creation, prototype chain, data type detection, inheritance)
Copy code The code is as follows:

/****************** 객체지향 ******************/
/********** 1: 객체 생성, 프로토타입 체인 **********/
/* 객체를 생성하기 위해서는 생성자(클래스 메소드)에 대해 논의하고 그 내용을 심도 있게 이해하는 것이 중요합니다
*/
function MyFunc() { }; //빈 함수 정의
var anObj = new MyFunc() //new 연산자를 사용하고 MyFun 함수를 사용하여 객체 생성
/ /동일함:
function MyFunc() { };
var anObj = {}; //객체 생성
anObj.__proto__ = MyFunc.call(anObj) /anObj 객체를 이 포인터로 사용하여 MyFunc 함수를 호출합니다.
/*
var anObject = new aFunction() 형식의 객체를 생성하는 프로세스는 실제로 세 단계로 나눌 수 있습니다.
1단계 : 새 개체(anObject)를 만듭니다.
2단계: 개체의 내장 프로토타입 개체(__proto__)를 생성자 프로토타입에서 참조하는 프로토타입 개체로 설정합니다.
3단계: 개체를 사용하여 생성자를 호출합니다. 매개변수, 멤버 설정 등 초기화 작업을 완료합니다.
객체가 생성된 후 객체에 대한 모든 액세스 및 작업은 객체 자체 및 프로토타입 체인의 객체 문자열에만 관련됩니다.
생성자와는 아무런 관련이 없습니다.
즉, 생성자는 객체 생성 시 프로토타입 객체를 도입하고 객체를 초기화하는 역할만 합니다.
프로토타입 체인: (참조: http://hi.baidu.com/fegro/blog/item/41ec7ca70cdb98e59152eed0.html)
각 객체(여기서의 객체는 중괄호 안에 있는 객체만 참조해야 하며, 함수, 배열 포함? )
는 __proto__라는 속성을 초기화합니다. 객체의 속성에 액세스하면
이 속성이 객체 내부에 존재하지 않으면 검색됩니다. __proto__의 이 속성,
이 __proto__에는 자체 __proto__가 있으므로 계속해서 이를 찾는데, 이것이 바로 우리가 일반적으로 프로토타입 체인의 개념이라고 부르는 것입니다.
*/
/* 객체 생성 원리를 이해한 후 아래 두 예제의 결과를 분석해 볼 수 있습니다*/
var yx01 = new function() {return "Circle Center"};
alert (yx01); // [객체 객체]
var yx02 = new function() {return new String("center of Circle")}
alert(yx02); Circle"
/* 설명 :
"Circle Center"는 기본 문자열 타입이고, new String("Circle Center")은 문자열 객체를 생성합니다.
new 표현식 뒤의 생성자가 참조 객체(배열, 객체, 함수 등)를 반환하는 한, new로 생성된 객체를 덮어씁니다.
기본 유형을 반환하는 경우(해당 항목이 없는 경우) 반환하면 실제로는 기본 유형인 정의되지 않은 값을 반환합니다.
그런 다음 new로 생성된 객체를 반환합니다.
참고: http://www.planabc.net/2008/02/20/javascript_new_function/
*/
/********** 2: 데이터 유형 감지 **********/
/* 데이터 유형 판단 방법:
constructor, typeof, instanceof, Object.prototype.toString.call()
*/
/***** 1. 생성자 속성을 통해 *****/
var myvar= new Array(" a"," b","c","d");
함수 A(){}
myvar.constructor = A;
var c = myvar.constructor;
alert(c ); // function A(){}
//생성자 속성을 통해 유형을 얻는 방법은 쉽게 수정될 수 있으므로 유형을 결정하는 데 사용해서는 안 된다는 것을 알 수 있습니다.
/***** 2. typeof를 통해 *****/
/*
typeof는 함수가 아니라 연산자입니다.
typeof의 실제 적용은 객체가 정의되었거나 값이 할당되었는지 여부를 감지하는 것입니다.
예를 들어 if(typeof a!="undefine"){}인 경우 if(a)를 사용하지 마세요. a가 존재하지 않으면(선언되지 않음) 오류가 발생하기 때문입니다.
typeof가 객체 유형을 감지하면 일반적으로
number, boolean, string, function, object, unundefined 결과만 반환할 수 있습니다.
배열, Null, 사용자 정의 개체 등에 typeof를 사용하면 항상 개체가 반환됩니다.
이것이 typeof의 제한 사항입니다.
*/
var num = new Number(1);
var arr = [1,2,3]
alert(typeof num)
alert (typeof arr); //배열 대신 객체
alert(typeof null); // object
/***** 3. 인스턴스 오브를 통해 *****/
/* 객체가 객체인지 확인하려면 objectof 연산자를 사용하세요. 클래스의 인스턴스.
obj instanceof Class가 true를 반환하면 Class의 프로토타입은 obj 프로토타입 체인의 프로토타입과 동일한 객체입니다.
즉, obj는 Class 또는 Class의 하위 클래스에 의해 생성됩니다.
*/
function t(){};
t.prototype = Array.prototype;
//t.prototype = []
var x = new
alert(x 인스턴스of t);//pop true
alert(x 인스턴스of Array);//pop true
alert(x 인스턴스of Object);//pop true
/*
by instanceof를 통해 데이터 유형을 판단하는 것도 신뢰할 수 없음을 알 수 있습니다.
객체(여기서 x)의 프로토타입 체인은 매우 길 수 있으므로 각 프로토타입의 유형이 다를 수 있습니다.
또한 iframe 내에서는 오류가 발생하기 쉽습니다.
즉, 배열 a를 정의하는 페이지가 있고 해당 페이지에 배열의 top.a 인스턴스가 중첩되어 있습니다. Iframe에 전달되면 false를 반환합니다.
이 설명은 상위 페이지와 포함된 iframe의 개체가 다르며 함께 혼합될 수 없음을 나타냅니다.
Changed to top.a instanceof top.Array will return true
*/
/***** 4. Through Object.prototype.toString.call() *****/
/*
Object.prototype.toString.call() Function It is:
1. Get the class name (object type) of the object.
2. Then combine [object, obtained class name] and return it.
Can be used to determine objects of Array, Date, Function and other types
*/
var num = new Number(1);
var arr = [1,2,3];
alert(Object.prototype.toString.call(num)); // [object Number]
alert(Object.prototype.toString.call(arr)); // [object Array]
// Extended example : (apply is equivalent to call)
window.utils = {
toString: Object.prototype.toString,
isObject: function (obj) {
return this.toString.apply(obj) = == '[object Object]';
},
isFunction: function (obj) {
return this.toString.apply(obj) === '[object Function]';
} ,
isArray: function (obj) {
return this.toString.apply(obj) === '[object Array]';
}
}
function A() { }
window.utils.isFunction(A); //true
window.utils.isObject(new A()); //true
window.utils.isArray([]); //true
/*
Frameworks such as jQuery use this method to determine the type of objects, so this method can be used as an authoritative judgment method.
However, if the Object.prototype.toString method is overridden, errors may occur when using it to determine the data type.
So, generally do not override the Object.prototype.toString method.
*/
/********** Three: Inheritance **********/
/*
JS inheritance, like closures, is an issue that almost every friend who wants to learn JS in depth has to discuss, so various All relevant information is available.
There are many versions of JS inheritance code, but the principles are the same, and the core uses prototype objects.
In order to be similar to the style of other object-oriented languages, most of them use "class" style simulation.
The detailed principles of inheritance will not be described in detail. There is a lot of information on the Internet.
Here is an example: inheritance written by Jquery author John Resig.
(The detailed comments are from a blog, I don’t know who created it, so I repost it privately here)
*/
(function () {
// initializing variables are used to mark the current Whether it is in the creation phase of the class,
// - The prototype method init cannot be called during the creation phase of the class
// - We have elaborated on this issue in the third article of this series
// fnTest is a regular expression, the possible values ​​are (/b_superb/ or /.*/)
// - The test of /xyz/.test(function() { xyz; }) is to detect Does the browser support the case where the test parameter is a function?
// - But I tested IE7.0, Chrome2.0, and FF3.5, and this test all returned true.
// - So I want this. Assigning a value to fnTest is correct in most cases: fnTest = /b_superb/;
var initializing = false, fnTest = /xyz/.test(function () { xyz; }) ? /b_superb/ : /.*/ ;
// Base class constructor
// This here is window, so this entire code opens a window to the outside world - window.Class
this.Class = function () { } ;
// Inherited method definition
Class.extend = function (prop) {
// This place is very confusing, remember what I mentioned in the second article of this series
// - What this specifically points to cannot be determined at the time of definition, but depends on how this function is called
// - We already know that extend must be called as a method, not as a constructor
// - So here this points not to Object, but to Function (i.e. Class), then this.prototype is the prototype object of the parent class
// - Note: _super points to the prototype object of the parent class, we will I encountered this variable many times in the following code
var _super = this.prototype;
// Inheritance is completed by pointing the prototype of the subclass to an instance object of the parent class
// - Note: this It is the base class constructor (i.e. Class)
initializing = true;
var prototype = new this();
initializing = false;
// I think this code has been optimized by the author , so it reads very bluntly, I will explain it in detail later
for (var name in prop) {
prototype[name] = typeof prop[name] == "function" &&
typeof _super[name ] == "function" && fnTest.test(prop[name]) ?
(function (name, fn) {
return function () {
var tmp = this._super; // here is If necessary, the comment code on line 91 can explain it.
this._super = _super[name];
var ret = fn.apply(this, arguments);
this._super = tmp;
return ret;
};
})(name, prop[name]):
prop[name];
}
// It can be seen from this place that Resig is very good at disguise
// - Use a local with the same name Variables to override global variables, it is very confusing
// - If you find it awkward to pronounce, you can use another name, such as function F() instead of function Class()
// - Note: here Class is not the base class constructor defined in the outermost layer
// The Class here is different from the window.Class function above. Here is the function local variable inside window.Class
function Class() {
// When instantiating a class, call the prototype method init
if (!initializing && this.init)
this.init.apply(this, arguments);
}
// The prototype of the subclass points to the instance of the parent class (the key to complete inheritance)
Class.prototype = prototype; // Class refers to the Class above, not the initial window.Class
// Fix the constructor pointing error
// Can it be corrected by using Class.prototype.constructor = Class;? ? ?
Class.constructor = Class;
// The subclass automatically obtains the extend method, arguments.callee points to the currently executing function
Class.extend = arguments.callee;
return Class;
};
})();
Statement:
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