First JavaScript
- JavaScript first appeared in 1996 as part of the Netscape Navigetor browser, originally designed to improve the user experience of web pages by Brendan Eich
- JavaScript was originally named liveScript, but was later changed to JavaScript by Son
Browser Composition
- There are two parts to the browser, the shell and the kernel, and the kernel contains a lot of things.
- The Neheli rendering engine is responsible for the HTML and CSS sections, defining syntax rules, rendering rules, rendering paths and speeds, and so on.
- JS engine, released in 2001 IE6, the first implementation of JS engine optimization.
- In 2008, Google released Chrome, it is the use of optimized JS engine, engine code V8, because of the JS code directly into the mechanical code 0101 to execute, and is known for its speed.
- Later, Firefox also introduced a powerful JS engine.
JavaScript features
- Interpreted languages –> Do not need to compile code, can be cross-platform, like PHP, JS, JSP are interpreted languages.
- Single thread can execute only one thing at a time.
- ECMA standard -> In order to unify the rules of JS, the ECMA standard is introduced, so JS is also called ECMAScript.
JavaScript consists of ECMAScript, DOM, and BOM
- ECMAScript is a basic JaveScript that conforms to the ECMA standard.
- DOM is the Docmengt Object Model document Object Model that can be used to do HTML and CSS parts (very important parts).
- BOM is the Browser Object Model that operates the Browser shell. Because each Browser is different, we operate BOM differently in each Browser
Basic syntax for JaveSctipt
- Variable declarations
- JS is a weak data type language, variables of any type are declared with key child var
var arr = [1.2.3];
var num = 123;
var str = "abc";
Copy the code
- An assignment can be made at the same time as the declaration or after it
var num = 123; // num=123
var num;
num = 123; // num=123
// Both methods are the same
Copy the code
- There is also a single VAR pattern
var num1 = 123,
num2 = 234
num3 = 345;
// Align the variable names up and down to make the structure clearer and save a lot of code.
Copy the code
- Variable naming rules
- Start with a letter or underscore or $.
- Variable names can contain numbers.
- Do not use the default keyword or reserved keyword.
- Value type (data type)
- Immutable original value.
- There are Numberf, String, Boolean, undefined, and NULL heap data.
- Reference value Array, Object, and Function stack data.
Basic rules for JaveScript statements
- The statement is followed by a semicolon (;). The end of the
- JS syntax errors cause subsequent code to terminate, but do not affect other JS code blocks
It is limited to logic errors and low-level syntax errors that cause the code to not execute at all.
3 Writing Specifications
JAaveScript operator.
- “+” mathematical addition function and string concatenation, “-, *, /, %” mathematical operations
- Same as “++, –, ==, +=, -=, >, <…” Etc.
- Logical operators &&, | |,!
- The && function is executed only if the result is true, the first error is not executed, and the last expression is returned if both are true
- | | role is as long as there is an expression is true don’t go back, and the returned result is the result of the correct expression, as a result of all falses expression returns false
&& can be used as a short statement, | | as initialization function
- The default value is False
- Undefined, null, NaN, 0, false
Type conversion
Explicit type conversion
- Typeof data can be detected with typeof
console.log(typeof(123)); // Number
- There are six types of results returned by Typeof:
Number
,String
,Boolean
,undefined
,Object
,Function
- Arrays and NULL are both objects
- NaN belongs to Number, which is a non-number but also a Number
- Typeof returns a string as a result
- parselent(string, radix)
- This method converts strings to integer type numbers, where the radix base is the optional argument.
- When a string contains both a numeric string and other strings, it will stop seeing other strings and will not continue converting numeric strings
parselnt('123abc123') / / 123;
parselnt('abc123') // NaNParselnt ('123')/ / 123
parselnt('true') // NaN
Copy the code
- This function can be used as a base conversion when the radix is not empty, converting the number of the first argument to decimal as a number of base digits
- The radix reference range is 2~36
var demo 10;
parselnt(demo,16) / / 16
Copy the code
- parseFloat(radix)
- This method is similar to parselnt in that it converts a string to a floating point number and stops at the first non-numeric type
- Only the first decimal point and subsequent digits can be identified. The second decimal point cannot be identified.
parseFloat('123.2.3'); / / 123.2
parseFloat('123.2 "ABC") ; / / 123.2 parseFloat ('123.abc1'); / / 123Copy the code
- toString(radix)
- This method is a method on an object that can be used by any data type, converted to a string type, and involves wrapping classes.
- Also the Radix base optional argument, empty only converts data to strings
var demo = 123;
typeof demo.toString(); // string/123
typeof true.toString(); // string/true
Copy the code
- When the radix is written, it means converting this number to a numeric string of several bases
var demo = 10;
demo.toString(16); // A
Copy the code
- Undefined and NULL have no toString methods
- number(mix)
- This method can convert other types of data to numeric type data
- string(mix)
- Just like the number method converts any type to a string
- boolean(mix)
- Just like number converts any type to Boolean
Implicit type conversion
- isNaN()
- This method checks if the number method is of a non-number type
- Arithmetic operator
++
You call number on the existing data, and you increment it by one+
,-
,*
,/
Before execution, the type is cast to a number
- Logical operator
&&
,||
,!
Boolean is called to convert to a Boolean value and return the result of its own expression
! abc; // false
- Comparison operator that does not convert
- === strictly equal to! == strictly does not equal
precompiled
- Function declaration promotion: A function declaration promotion is an overall promotion that brings both the function declaration and the function body to the front.
- Variable declaration promotion: Variable declaration promotion is a partial promotion that merely advances the declaration of variables, but does not promote assignments
- JS run trilogy
- Syntax analysis
- precompiled
- Explain to perform
- Precompilation prelude
- imply global
- Alluding to a global variable, if any variable is assigned an undeclared value, the variable is owned by the Window and becomes an attribute of the Window object
- All declared global variables are Window properties
- Undeclared global face changes can be deleted by the delete operation
- A function generates a context, an Activeaction Object, at the moment before execution
This object is empty, but it has some invisible implicit properties: the this:window attribute and arguments[]; attribute
- Precompile four
- Creating an AO Object
- Find the parameter and variable declarations and add them to the AO object as property names, with the value undefined. (Function declarations are not called variables)
- Unify the arguments and parameters
- Look for the function declaration in the function body, using the function name as the property name and the value as the function body
function test (a, b) {
console.logo(a)
function a () {}
a = 222;
console.log(a);
function b (){}
console.log(b)
var b = 111
var a;
}
test(1)
// 1 222 function
Copy the code
- Var b = function (){} var b = function (){}
- Finding the function declaration in step 4 does not assign function () {}, only the function is assigned when the line is executed
function
A function.
- Three ways to declare functions
- Function expression:
var demo = function (){};
- Function declaration:
function demo (){};
- Named function expressions:
var demo = function xxx(){};
- Each function has a class array property called Arguments, which holds arguments.
- Each function has a length attribute, which stores the number of parameters.
- Every function has a return, and if you don’t care, the function automatically adds a return
- A return has two functions: to return the result of the function’s execution, and to terminate the function’s execution
function test (a, b) {
console.log(a + b);
return;
console.log("hello");
}
test(1.2); // Prints result 3, not Hello
Copy the code
Scope
- Definition: variable (variable scope also called context) and function effect (can be accessed) area
- JavaScript functions can have scopes.
- In ES5, there are only two types of scope: global scope and functional scope. Es6 has a new block-level scope
var demo = 123; // Global variables
function test(){
var demo = 234; // Local variables
console.log(demo);
var demo = "hello";
}
test(demo) // log=>234 Print local variables nearby. Print global variables without local variables
console.log(demo); Global scope cannot access local scope
Copy the code
- The scope of a function is like a room in which the inside can take the outside and the outside can’t take the inside
- Declaring variables in a function scope without var generates a global variable
- Two different scopes (except for the global scope) are not mutually accessible
Scope chain
- Since a function has scope and can be nested, the scope directly generates the nesting relationship, which is the scope chain
- When code executes in an environment, a scope chain of variables is created to ensure orderly access to variables and functions that the execution environment has access to
- The first object in the scope chain is always the variable object of the environment in which the code is currently executing
function demo () {
var dome_a = 1;
function test () {
var demo_a = 2;
console.log(demo_a);
}
test();
}
demo();
Copy the code
- With privileged and ordered access to the execution environment, each function operates at the top level of its scope, followed by its parent function scope…. Up to the global scope.
- So when test is executed, demo_A is 2 in its own scope, not 1. If there is no demo_A in its scope, the system will find dome_a down the scope chain
4. Closure
- What is a closure
Closures are functions that can read variables inside other functions
- Different scopes cannot access each other, but if you define a function inside a function that is associated with a variable in the outer function. You can then return this function to access variables inside the outer function, so a closure is essentially a bridge between the inside of the function and the outside of the function.
function a (){
var dome1 = 123;
add = function (){
dome1 ++;
}
return function (){
console.log(dome1; }}var demo = a();
demo(); / / 123
add();
demo(); / / 124
Copy the code
- When the function is finished executing, the execution context is destroyed, and the variables inside it cannot be accessed, but our function returns a new function that depends on the function. That is, the undestroyed new function’s scope chain contains references to the original function’s scope, so the context of the original function will not be destroyed, and the new function returned is the closure of the original function
- Considerations for using closures
- Closures will make the function variables are stored in memory, memory consumption is high, do not abuse, otherwise it will cause web performance problems, IE will cause memory leaks
The solution is to remove unused local variables when exiting a function
- Closures change the values inside the parent function outside of the parent function. If you use a closure as an object, treat the closure as its public method and internal variables as its private properties.
var name = 'global';
var obj = {
name:'obj'.getNamu: function(){
return function () {
console.log(this.name)
}
}
}
ogj.getName()();// obj
Copy the code
- accumulator
function a (){
var num = 1;
function addNum (){
num ++;
console.log(num)
}
return addNum;
}
var demo = a();
demo(); / / 2
demo(); / / 3
var demo1 = a();
demo1(); / / 2
demo1(); / / 3
Copy the code
Execute the function immediately
- An important way to unwrap a closure when executing a function immediately, but note that there is no way to touch a closure, and only a new closure can undo the effects of the previous one
- The immediate function does not need to be defined. It is executed directly and released after execution. It is often used for initialization
- Function declarations cannot be executed, but function expressions can
(functiion (){});
Copy the code
function retruB (){
var arr = [];
for(i = 0; i < 10; i++){
arr[i] = (function(){
console.log(i)
})
}
return arr;
}
var save = returnB();
consosle.log(save);
for(j = 0; j < 10; j++){
save[i];
}
Copy the code
object
- How objects are created
- Object literals
var obj = {};
- This way is the simplest and most common method
- Properties are separated by commas. Each property has a property name and value, which are separated by semicolons
- Constructors
- Constructors are also divided into two types, the system’s own constructors and custom constructors
- Create Object constructor Object()
var object = new Object();
Var obj = {}; var obj = {}; Have the same effect as
- Number(), String(), Boolean(), Array()
- Custom constructors
- A custom constructor is the most commonly used constructor
var function Person(){};
var operson = enw Person();
typeof operson // object
Copy the code
- Objects created with the new operator are not associated with each other, even though they are given constructors.
function Person (name, age) {
this.name = name;
thia.age = age;
}
var person = new Person('zhangsan'.18);
console.log(person.name);
Copy the code
- When you create an object, only new will have this
- Important: Can you use the new operator to create separate objects for life?
- When we use the new operator, the new creates a this object inside the constructor and returns the this object
function Person (name) {
var that = {
name: 'list'
};
that.name = name;
return that;
}
var person = new Person('demo');
console.log(person.name)
Copy the code
- If the object is returned, this is invalid, but if the original value is returned, this is still valid.
- Add, delete, change and check attributes
- Add: You can add new attributes and assign values to objects by using the object name + dot + attribute name method
var ogj = {
name:'demo',
}
obj,mame = 'tan';
Copy the code
- Search: View properties
console.log(xxx)
- Delete: Deleting an attribute requires the delete operator
var obj = {
name = 'scerlett'
}
obj.name; // scerlett
delete obj.name;
obj.name; // undefined
Copy the code
Prototype and prototype chain
I’m a prototype
- Definition of a stereotype: A stereotype is a property of the function object that defines the common ancestor of the objects produced by the constructor.
- You can inherit the properties and methods of the stereotype, which is also an object.
function Person(){}
- Define a constructor. The Person.prototype property is the prototype of this constructor, and is inherent in this property and its value is an object.
- You can add properties and methods to Person.Prototype, and each constructed object can inherit these properties and methods
- Although each object is independent, they all have a common ancestor. When accessing an object property, if it does not have the property, it will look up, find its prototype, and then access the property on the prototype
- Using the concept of prototype characteristics, common attributes can be extracted
- Instead of writing the public properties of every object in the constructor, we can extract them from the prototype, so that when the constructor constructs a large number of objects, it does not have to go through the constructor assignment statement multiple times.
- You can just go through it once and look it up directly on the prototype for each object that calls the property.
- Object viewing prototype
- When you use a constructor to construct an object, you implicitly create a this object with a default property called the proto property. The value of this property refers to the prototype of the object.
- When you look for a property that you don’t have, you look for the property proto, and that property points to the prototype, so you look for the property on the prototype.
Note: Prototype is a function property; proto is an object property
- Look at the constructor that builds itself
- In Prototype, there is an implicit property called constructor that records the object’s constructor and holds the constructor inside
console.log(person.constructor); // function Person(){}
Prototype chain
- With a prototype, the prototype is still an object, so the object named prototype naturally has its own prototype, such prototype and the mechanism of the prototype constitute the prototype chain
Gra.prototype.firsName = 'scarlett'
function Gra () {
this.name = 'grandfather';
this.sex = 'male';
}
var grandfoo = new Gra();
grandfoo.word = 'hello';
Foo.prototoype = grandfoo;
function Foo(){
this.age = '18';
this.moner = '100';
}
var father = new Foo();
function Son() {
this.name = 'son';
}
Son.prototype = father;
var son = new Son();
Copy the code
- Every object created by Foo inherits from Grandfoo, and every object created by son inherits from father, an object created by Foo, so that son can inherit all properties of Foo and Gra.
- This type of chained query structure is called a prototype chain, which ends with the Object. Prototype
- If there is no specified prototype Object, its prototype is Object.prototype
- But not all objects have prototypes, such as using the object.create method
- The object.create () method takes an argument that looks at the prototype of the Object hi to construct a sum
var obj = {};
For the same object, write:var obj = Object.create(Object.prototype);
- You can also write a custom attribute and make it a prototype
- The one on the prototype chain was deleted
Person.prototype.arr[1.2.3];
var person1 = new Person();
var person2 = new Person();
person1.arr.push(4);
console.log(person2); / / 1234
Copy the code
- Delete: Deleting properties requires the delete operator. Objects cannot delete properties from prototypes
- Change:
- Check:
Inheritance, this
- Some questions about this
- This inside the function points to the window by default. You can use call/apply to change the reference of this
- Differences: Different forms of the following parameters
- Apply puts the parameters in an array
function person (){
this.name = 'scarlett';
console.log(this);
}
person();
// This refers to the window, and the name attribute is the global attribute of the window
var obj = {};
person.call(obj); // Object.{name:'scarlett'}
Copy the code
- inheritance
- The holy grail mode
var inherit = (function (Target, Origin) {
function F(){};
return function (Target, Origin){
F.prototype = Origin.prototype;
Target.prototype = new F();
Target.prototype.constuctor = Target;
Target.prototype.uber = Origin.prototype;
}
}());
Copy the code
Object enumeration with this
- Enumeration of objects
- View object properties using
obj.name
Check, you can also useobj['name']
Like an array, but in fact arrays mimic the way objects are viewed
- The for – the in operator
- Enumerating all the properties of an array is done through a for loop, but objects cannot iterate through properties through a for loop, so a for-in operation is used
var obj = {
name: 'scarlett'.age: 18.sex:'female'
}
for(var prop in obj){
console.log(prop + ':' + obj[prop]);
}
Copy the code
- The for-in loop is going to fetch the property names in the property order and then it’s going to assign to the variable prop, all printed prop are property names,
obj[prop]
Is the value of the corresponding property.
Note: this cannot be written as obj. Prot because it is converted to obj[prop] at the bottom of the system, but there is no prop property, it is just a variable.
- In non-strict mode, for-in loops print out some properties of the prototype together, but in ES5 strict mode they do not.
- Three operators
- The hasOwnProperty operator checks whether the current property is a property of the object itself. Properties on the prototype chain are filtered out and return true
function Person(){
this.name = 'scarlett';
}
Person.prototype = {
age: 18
}
var oPerson = new Person();
for(var prop in oPerson){
if(oPerson.hasOwnProperty(prop)){
console.log(oPerson[prop]); }}Copy the code
-
The for-in loop will print only its own properties, not those on the prototype
-
The in operator: This operator checks whether an attribute is in the object or its stereotype.
'name' in oPerson; // true
'sex' in oPerson; // false
Copy the code
- The instanceof operator: checks to see if the preceding object was constructed by the following constructor, much like constructor.
oPerson instanceof Object; // true
{} instanceof oPerson; // false
Copy the code
- this
- This points to the window during precompilation
- This points to the window in the global scope
- Call /apply can change the this reference
- Obj.func () This in func() refers to the object obj
var obj = {
height: 190.eat: function () {
this.height ++; // eat no one knows who this refers to until executed
}
}
obj.eat(); // Who calls this refers to
Copy the code
- If you understand that this refers to the problem in the following code, then you know everything about this
var name = '222';
var a = {
name: '111'.say: function (){
console.log(this.name); }}var fun = a.say;
fun(); // '222' assigns the body of a.say to fun. This refers to the window.
a.say(); // this refers to whoever is called by '111'
var b = {
name: '333'.say: function (fun) {
fun();
}
}
b.say(a.say); // how does' 222 'actually call the body method of a.say globallyB.s ay = a.s ay; b.say();// '333' this points to B
Copy the code
Cloning and Arrays
- arguments.callee()
- Refers to the function itself, when the function itself is called recursively from some anonymous or immediate function, because it has no name.
- It is common to write an immediate function when initialization is computed, and to call it this way when the immediate function also needs to recursively call itself.
- function.caller()
function test (){
console.log(test.caller);
}
function demo (){
test();
}
demo();
Copy the code
- This is a built-in property of the function itself, which indicates a function reference to the uber environment of the current function, which is executed within that function.
- Clone (s)
- There are some differences between cloning and inheritance. Cloning is to copy the same target object and divide it into shallow clone and deep clone
function clone (src, tar) {
var tar = tar || {};
for (var prop in src) {
if(src.hasOwnProperty(prop)){
tar[prop] = src[[prop];
}
}
return tar;
}
Copy the code
- When an attribute is a reference value (array, object) according to this cloning mode, only the heap address of the reference value is assigned to the new target object. Once the reference attribute of the source object or target object is changed, the other one also changes, which is the disadvantage of shallow cloning.
- The principle of deep cloning is very simple, as long as the reference value is regarded as a source object instead of cloning the reference value, and the values inside are cloned into the target object one by one, the problem of the two pointing to the same can be solved
function deepCopy(src, str) {
var tar = tar || {};
for(var prop in src) {
if(typeof(src[prop] == 'object')){
tar[prop] = (src[prop].constructor === Array)? [] : {};return deepCopy(tar[prop], src[prop]);
}else{ tar[prop] = src[prop]; }}return tar;
}
Copy the code
- The reference values of the target object and the source object are independent and can be modified.
- Array (arrTY)
- Arrays can be declared in two ways: literals and array constructors
var arr = new Array(1.2.3.4);
console.log(arr) / / 1, 2, 3, 4
Copy the code
Note: if the constructor argument is a single number, then this is not the first value, but the length of the array
- Js arrays are weakly typed arrays that cannot overflow read, but can overflow write
var arr = [1.2];
console.log(arr[3]); // undefined
arr[5] = 5;
console.log(arr); / / 1, 2,... 5
Copy the code
- Common methods of arrays: immutable array and change array
- Change the original array:
reverse
Invert the arraysort
Quick sortpush
Adds data at the end of the arraypop
Deletes from the last bit of the array and returns the deleted datashift
Deleting from the first digit of an array returns the deleted dataunshift
Add data before the first digit of the arraysplice
Intercept, three parameters. The first is the position at which the interception began, the second is the length of the interception, and the third is a set of data at which data is added
var arr = [1.2.3.4.5];
arr.solice[1.2.100.200];
console.log(arr) / / 5-tetrafluorobenzoic [1100200]
Copy the code
+ 'sort' it wraps an algorithm number for us to use. You can pass in a parameter to this method. This parameter is a function that specifies pAIX rules, otherwise sort by ASC code. Js arr.sort(function (x, y){return x.age < y.age; }) ` ` ` + x, y represent two arbitrary data in the data, no matter the middle rules how to write, finally returned to the value of the system only focus on function, it is positive or negative, positive when said y x in front and behind negative said x b + out-of-order behind before ordering: Js function order (a, b) {var num = math.random () -0.5 return num; } ` ` `Copy the code
- You cannot change the original array
concat
This is what arrays are for, if you want to concatenate multiple arrays with commas between them
var arr1 = [1.2]; var arr2 = [3.4]; arr1 = arr1.concat(arr2); / / arr1 = > [1, 2, 3, 4] Copy the code
join
How to concatenate each piece of data in an array into a string
var arr1 = ['a'.'b'.'c'.'1']; arr1 = arr1.join(The '-') console.log(arr1) // a-b-c-1 Copy the code
split
Just andjoin
Instead, how to split string one into arrays
var sta = 'How are you'; var arr = sta.split("".2); // arr => ['How', 'are'] Copy the code
- Array to heavy
Array.prototype.unique = function (){
var len = this.length,
arr = [],
obj = {};
for(var i = 0; i < len; i++) {
if(! obj[this[i]]){
obj[this[i]] = 1;
arr.push(this[i]; }}return arr;
}
var arr = [1.1.2.3.2.3.21.23.57.323.4];
console.log(arr.unique()); //
Copy the code
- A simple hash structure is used here. When the data in the array appears once, obj treats the element as an attribute and assigns it a value of 1. If the same element appears later, because it already exists in obj and has a value of 1, it will not be added to the new array, and the new array will be returned.
- ES5 array methods:
forEach
It changes the array so that the elements in the array are iterated through, each one is called, and the argument to forEach is a function.map
Like forEach, forEach changes the array, map does not change the array, 24 returns a new array, and the argument is a function.filter
The filter does not alter the array. Instead, it returns a subset of the value of the array. A function that returns true adds the current element to the new array, and a function that returns false does not add the current element to the new arrayevery
andsome
The heap array is evaluated using the specified function and returns true or false. Every returns true if each element is passed true. Some returns true if another element is passed truereduce
andreduceRight
The specified function is used to combine the array elements into a single value, reducing from left to right.
ReduceRight is from right to left, with two parameters, the first is method, the second is optional parameter, that is, the last value is the initial value, when no parameter is set, the value of the first element of the array is used as the initial value, but when the array is empty, no initial value will be reported. If the array has only one element and no initial value is specified, or if there is an empty array and an initial value is specified, reduce simply returns that value and does not skip the function
var arr = [1.2.3]; var sum = a.reduce(function (x,y){return x + y},0); // 0 + 1 + 2 +3 = 6 var temp = [1]; var tempOut = a.reduce(function(x,y){return x * y}); // 1 will not call this function because the array has only one value unless an initial value is set Copy the code
- Array type detection
- In ES5, there is an isArray() method to check for arrays, but it is cumbersome to check for data types before ES5
Typeof operators: Both arrays and objects return object. There is no way to distinguish arrays from objects
- The constructor and instanceof operators are currently best used, but both have potential problems
A Web browser may have multiple Windows or forms, each form has its own JS environment, its own global object, and each global object has its own constructor, so objects in one form will not be possible to be a real column of constructors in another form, and confusion between forms does not often occur. But this problem has proven that neither Constructor nor Instanceof can really reliably detect array types.
Object.prototype.toString.call(arr) // => '[Object Array]'
// This is the most reliable way to check if it is an array type
Copy the code
Class arrays with strict schemas
- There are two types of data called arrays and objects. You can use objects to simulate the effect of original arrays. These objects are called class arrays
- Class array:
- A class array is not an array, but it can behave like an array
var arrObj = {
'0': 1.'1': 2.'3': 3.'length': 3.'push':Array.prototype.push
}
// This creates an array of classes
arrObj.push(4);
console.log(arrObj);
// ---->>
/*var arrObj = { '0': 1, '1': 2, '2': 3, '3': 4, 'length': 3, 'push':Array.prototype.push }*/
Copy the code
- It automatically changes the value of length. In fact, the key of the class array is the length attribute. If there is no length attribute, then it is an ordinary object, even if there is a push object, it cannot be used
- The realization principle of array push method is simulated
Array..prototype.push = function (num ) {
this[this.length ++ ] = num;
}
Copy the code
- The push method is to add a value to the end of the array, that is, an element at length, and then add length by one. It is easy to understand why an object with length can call the push method of the array, because it has a valid length property.
var arrObj = {
'3': 1.'4': 2.'a': 3.'b': 4.'length':2.'push':Array.prototype.push
}
arrObj.push(3);
arrObj.push(6);
/*var arrObj = { '2': 3, '3': 6, '4': 2, 'a': 3, 'b': 4, 'length':4, 'push':Array.prototype.push }*/
Copy the code
- try… catch
- try{}catcj(e){}; Finally {} is usually used to detect problems that might go wrong. You can put the code that might go wrong ina try, and then put the code that might react to a weak country’s error ina catch.
- The parameter E in catch must be present, and the system will automatically send error messages, which are generally divided into six types:
- The use and definition of EvalError eval() are inconsistent
- The RangeError array is out of bounds
- ReferenceError Indicates an invalid or unrecognized reference value
- SyntaxErroe has a syntax parsing error
- TypeError The operand type is incorrect
URIError URI handler is used improperly
- When the code inside a try fails, the code behind the error inside the try will not execute, but the code outside the try will execute normally
try{
console.log(a);
}catch(e){
console.log(e) // ReferenceError:a is not defined
Copy the code
- ES5 Strict mode
-
The ES5 strict mode is a new ES5 specification in which some of the ES3 non-standard rules cannot be used
-
Just say “use strict”; This line of string can enter strict mode, not heap incompatible strict mode browser impact, as long as there are two uses:
- Global strict mode: on I is negotiated on the first line of JS code · not recommended
- Local strict mode: Write the string on the first line of the function
-
The role of strict patterns
- When code is in strict mode, it is not allowed to use the with function, arguments.callee method, and function.caller attribute
- Must be used before variable assignment
- Local this must be assigned before it is used. The default value is undefined except for the global this, which points to window by default, and in non-strict mode after Person.call(null/undefined), this still points to window. But if you pass null/undefined in strict mode, this points to null/undefined
- Duplicate properties and arguments are rejected, although some browsers can duplicate property names
-
The with method changes the scope chain by placing the execution-time context or scope in parentheses at the top of its scope
var obj = [a:123};
function test () {
var a = 111;
var b = 222;
with(obj){
console.log(a); / / 123
console.log(b); / / 222
}
test();
}
Copy the code
- In the test function, the top of the scope chain would be “from”, and the next would be “window”, but with would call “a” in obj first
DOM began
- Document Object Model the DOM defines the objects needed to represent and modify a Document, their behavior and properties, and the relationships between them
- Dom objects are host objects, a class of objects and collections that manipulate HTML and CSS functionality defined by browser vendors, most of whom follow W3C rules
- How does dom manipulate HTML
- Document represents the entire document, which is also a DOM element, and does not allow HTML to be added, deleted, or looked up
- CSS has selectors such as ID and class tags, and many documeng objects define similar methods for viewing element nodes.
- getElementById
- document.getElementById(‘id); The method selects the corresponding element by its ID, which is a unique identifier. In browsers below IE8, it is case insensitive and can be selected as id by name
- getElementsByClassName
- We get an array of classes, because many elements can have a class name, and we can specify that element through the method [].
- getElementsByTagName
- A collection of elements selected by tag name
- getElementsByName
- Only some tags are applicable: forms, form elements, IMG, iframe, etc
- The most common ones here are getElementById and getElementsByTagName because all browsers support it
- QuerySelector () and querySelectorAll ()
- The strongest element selector is CSS, and the arguments written in these two elements are how CSS selectors are written
- But querySelector always picks the first one in a set, so instead of returning an array of classes it’s returning a concrete element and if you want to return an array of classes you just call it querySelectorAll().
- The problem with these two methods, however, is that they do not return a real-time element like the first four, but rather a copy of the selected element, which does not change its own element
Node 2.
- The node type
- Element nodes, text nodes, comment nodes, attribute nodes, etc. You can view the nodeType using the nodeType attribute. NodeType returns a number
- Element node –> 1
- Property node –> 2
- Text node –> 3
- Comment node –> 8
- docuemnt —> 9
- DocumentFragment —> 11
- Other properties of the node
- The nodeName property returns the label name of the element, in uppercase, read-only.
- There are several special nodes that return differently
- Text node –> #text
- Document node –> #document
- NodeValue Text Specifies the Text content of a node or Comment node, which can be read and written
- Attributes reads the inter-line style attributes and returns them in an object where each attribute is a node. This node is the attribute node
Note: Properties in objects are called properties, while properties in elements are called attributes, which should be called properties
- Nodes also have a method: hasChildNodes(), which checks for nodes
- Walk through the node tree
parentNode
Find the parent nodechildNodes
Child nodesfirstChild
First child nodelastChild
The last child nodenextSibliing
Next sibling nodepreviousSibling
Last sibling node
These methods are compatible and supported by all browsers.
- The tree is traversed based on the element
parentElement
Returns the parent element node of the current element, showing off the parent element in HTML is not a null docuent, IE does not support this!!children
All child element nodes, this method is compatible with all browserschildElementCount
Node.children. length === Node.childelementCount, this attribute is the number of nodes in the hi child element, usually children.NextElementSibling and previousElementSibling
These two are respectively to find the previous and next sibling elements, IE is not compatible!!
DO tree summary
- The getID method definition is not available on Document.prototype (Element).
- The getElementByName method is defined on htmlDocument. prototype. Documents that are not HTML cannot be used (XMD Document, Element).
- The getElementsByTagName method is defined on document. prototype and element. prototype. Documents and elements can use this method
- Htmldocument. prototype defines some common attributes, body and head respectively represent the corresponding tags in HTML documents
- The document.Element attribute is defined on document.prototype to refer to the < HTML > tag of the Document’s root Element
- GetElementByClassName, Query Selector All, quuerySelector, and Document and Element classes are All defined
Basic dom operation code
- The basics of DOM were introduced earlier, and here are some assembly functions for that knowledge
- Walk through the element node tree
function retChild(node){
var child = node.childNodes,
len = child.length;
}
Copy the code