Some understanding of the Javascript

1. Copy

     1.1 shallow copy

      First we look at the following code segment:

	var obj1 = {
		name: 'HHH',
        age: 20,
        sex: '男',
        dog: {
        name: '金毛',
        age: 2,
        yellow: '黄色'
        }
    }
	var obj2= {};
	//封装函数 将o1中的成员复制给o2
	function copy(o1, o2) {  
		for (var key in o1) {
			o2[key] = o1[key];
			}
        }
	//调用函数
	copy(obj1, obj2);
	//修改obj1中的成员
	obj1.name = 'pgone';
	obj1.dog.name = '阿毛';
	//打印obj2的属性
	 console.dir(obj2);

      Above this function, we create an object obj1, and then package a copy function, in obj1 we then create a property of the object dog, then assign him some property. After the wrapper function call, obj2 NATURAL successful copy, and at this time obj2 obj1 exactly the same properties. After calling, modify the members of the parent object found its own property can not be modified, while the sub-objects (property) in the properties can be modified. This is what causes it? Below using a parsing object relational graph.

Here Insert Picture Description
      obj1 added to a dog's property, it opens up a new memory space in memory to store the dog attribute and obj1 refer to memory addresses in the dog's dog. When we copied a similar obj2 object, its attributes dog still point to the same memory address, but does not replicate a dog object in memory, so a dog point to the same object, resulting in the above results. This is referred to as a shallow copy.

     Deep copy 1.2

      Using the same case above, we attach some properties. Prior to be understood as a pale plain copy just copied object layer. So deep copy, as the name implies, you can copy multiple layers.

var obj1 = {
	name: 'HHH',
	age: 20,
	sex: '男',
	dog: {
		name: '金毛',
		age: 2,
		yellow: '黄色'
		},
	friends: ['K9999', 'baebae']
	}
var obj2= {};
//封装函数 深拷贝将o1中的成员复制给o2
function deepCopy(o1, o2) {
	for (var key in o1) {
	//获取key属性对应的值
	var item = o1[key];
	//如果item是对象?
	if (item instanceof Object) {
		o2[key] = {};
		deepCopy(item, o2[key]);
		} else if (item instanceof Array) {
			//如果item是数组?
			o2[key] = [];
			deepCopy(item, o2[key]);
			}  else {
				//如果是简单类型
				o2[key] = o1[key];
                }                
            }
        }
	deepCopy(obj1, obj2);
	//修改obj1中的成员,是否会影响obj2?
	obj1.dog.name = '阿毛';
	obj1.friends[0] = 'AR';
	//查看obj2的属性
	console.dir(obj2);

       At this time, we print and found the child object attribute of obj2 property has not been changed, we continue to look at a problem from memory.
Here Insert Picture Description
       Recursive deep copy of the code, is different from the shallow copy problem child object in the object need to be considered. After this time the code is determined after object and the item object Array deep copy, also created in memory corresponding to its own memory, then the change will not change the properties obj1 obj2 attributes.

2.JS closure

       闭包是一个概念,不同的人对于其解释不同,这里我们查看MDN上的解释:函数与对其状态即词法环境(lexical environment)的引用共同构成闭包(closure)。也就是说,闭包可以让你从内部函数访问外部函数作用域。在JavaScript,函数在每次创建时生成闭包。
       我们简化一下就是:闭包是一个函数,是一个可以访问独立数据的函数。
       下面我们看一段代码段:

var name = 'PGONE';
var object = {
    name: 'My Object',
    getNameFunc: function () { 
    	var that = this; 
        return function () {  
            return that.name;
        };
    }
};
console.log(object.getNameFunc()());

       这里我们最后调用的位置就是全局作用域。首先调用getNameFunc返回一个函数function,第一处调用是object来调用,此是this指向object,所以that记录了object对象,所以第二次调用的时候返回that.name那么就是’My Object’。这里是否发生闭包了?在一个作用域中访问了另一个作用域的变量,确实发生了闭包。

3.遍历DOM树

       下面一段代码:

function loadTree(parent, callback) {  
    for (var i = 0; i < parent.children.length; i++) {
        //遍历第一级别子元素
        var child = parent.children[i];
        if(callback) {
            //处理找到的子元素
            callback(child);
        }
        //递归调用
        loadTree(child);
    }
}

var ul = document.getElementById('list');
loadTree(ul, function (element) {
    element.onclick = function () {
        console.log(this.innerText);
    }
});

       这里递归调用了body中的所有子元素。实际开发中我们需要将这些元素注册事件。可以通过回调函数不断回调从而不断遍历。我们通过获取元素之后就可以对其进行函数来注册事件。这对于实际的工作中是有用的。

4.正则表达式

       正则表达式是用于匹配字符串中字符组合的模式。在 JavaScript中,正则表达式也是对象。这些模式被用于 RegExp 的 exec 和 test 方法, 以及 String 的 match、matchAll、replace、search 和 split 方法。
       需要记住的是,RegExp对象中test()为匹配方法,exec()提取方法但是只提取一个内容。
       String对象中,match()也为提取,可以提取多个内容,如下代码:

var str1 = '[email protected], [email protected] 这是其他内容 [email protected] 2、[email protected] [email protected]...'; 
var reg = /\w+@\w+(\.\w+)+/g;
console.log(str1.match(reg));

       replace () alternative methods may be utilized regular expressions str.replace (/ \ s / g, '') below or split () method of splicing + join deletion substitute content. code show as below:

var str = '   123AD  asdsadsa     adf'    ;
console.log(str.replace(' ', ''));
console.log(str.replace(/\s/g, ''));
console.log(str.split(' ').join(''));

       The above is not used g (global) that is added to the back of the global variables in the positive expression of words, extracted from only the first content, the content is incomplete, it is noteworthy here.


Appendix some commonly used special characters and regular expression metacharacters:

Metacharacters Explanation
\d Matching numbers
\D Matches any non-numeric characters
\w Match letters or numbers or an underscore
\W Not match any letters, numbers, underscores
\s Matches any whitespace character
\S Matches any character is not whitespace
. Match any single character other than the line feed
^ Match the beginning of a line of text (this start)
$ Match Text end of the line (this end)

Qualifier Explanation
* Repeated zero or more times
+ Repeated one or more times
? Repeat zero or one time
{n} N times
{n,} Repeated n times or more
{n,m} To n times m times

Other special characters Explanation
[] It represents a character matches any meaning or equivalent
[^] In addition to matching the content in brackets
\ Escapes
| Alternatively, a selection of both
() Two quantities directly from a selected packet
Released two original articles · won praise 1 · views 239

Guess you like

Origin blog.csdn.net/AllEyezOnMewas/article/details/104433675