JavaScript Note

-----------------------------------------------------------------------Part Zero------------------------------------------------------------------
key : this, filter, map, reduce, let&const, arrow function, template literal, default parameter, object literal, rest and spread operator, destructor

Hoist [var] : every declaration w/ var in the function scope will be moved up to very top of function by default

Let : block scope, not hoisting

Const: constant, immutable

Arrow function:

 const xyz = () => n!

This :

> var emp = {
        id:1,
        greet: fucntion(){
             setTimeout( ()=> console.log(this.id),1000)
        }
  }

Default parameter : if argument specifies, then use argument, else, go with parameter

let getval = (val = 10) =>{
	console.log(xxxx)
}
getValue(20)
getValue(undefined)

Rest Operator: take args, and put it into an array

let msg = (message, ...color) =>{
   for(i in color){
        console.log(color[i])
   }
}
for (let c of color){
	xxxxx
}

Spread Operator: specifies at function call , takes array

let msg = (message, ...color) =>{
   for(i in color){
        console.log(color[i])
   }
}
let colorArr = ['Indigo','purple','jerkin']
msg('xyz', ...colorArr)

Object literal :

ES 5
let fName = "xyz"
let lName = "zzz"
let person = {
    fName: fName,
    lName: lName
}
        equivalent
ES 6
let person = {
	fName.
	lName,
	"Abc""bbc"
}
person["ABC"]

Destructuring Array, Object:

let emp = ["Eric", "Wang", "Male"]
// destrucuting arr into individual element
let [fname, lname, gender] = emp
// allow the nessary element to be destructuring 
let [, , gender] = emp
let [, ...element] = emp
// with default value 
let [fname, lname, gender, sideInfo ="lol"] = emp

**Object** 
let emp = {fName:"e",lName:"w"}
let {fName: f, lName:l} = emp

String Template:

let someTest = "hmm"
let msg = ` welcome to my page  ${someText}` 

class : just a function that is not hoisted

class Person{   // prototype : access global field 
	greet(){}   // adding a method to the class is same as adding an object to the class
}            
let p = new Person()
console.log(p.greet == Person.prototype.greet)

ES 5  => class can only contains methods, not objects 

class Person{
	constructor(name){
        this.name = name        // same as java
    }
    static staticMethod(){
       xxxxxxxxxxxx
    }
    greetPerson(){            // can be called by each object
       xxxx
    }
}
let p = new Person("Yo~~~~~~~~~")
Person.staticMethod()          // its scope is same as java


// Inheritance 
class Person{
	constructor(name){
	   xxx
    }
    xxx(){} 
}
class emp extends Person{
	constructor(name){
	   super(name)
    }
    xxx(){
        return super.xxx()
    }
}
let p = new emp("eric")
p.xxx()

Module : goal is to bring the seperation of concern together, just like the chapters in a book
is not buit-in to the ES5

  Module A     import function of B into A  with import keyWord
 
  Module B      function Export

  ES 6  name export, default export , export function , export class

  Module B
  export let fName = "chandler"
  export let lName = "cer"
  Module A
  import {fName, lName} from './moduleB.js'
  
  Module B
  let fName = "chandler"
  let lName = "cer"
  export {fName, lName}
  Module A
  import {fName, lName} from './moduleB.js'
  import {fName as f, lName as l} from './moduleB.js'

  import is read only, it cannot be overwrited, but object is an exception

  Default export
	
  Model B
  let fname = "xxxx"
  export default fname
  Model A
  import firstName from './modelB'   // name doesn't need to be matched
  import {default as firstName} from './modelB'


 
  export class and function
  Module B
  export function greet(msg){
      console.log(msg)
  }
  export class GreetMsg{
     constructor(){
        console.log("constructor")
     }
     greet(){
         console.log("xxxx")
     }
  }
  Module A
  import {greet, GreetMsg} from './moduleB.js'
  greet("xxx")
  let gm = new GreetMsg()

Set & Map

ES 5
let mySet = Object.create(null)
mySet.id = 0 
if(mySet.id){}

let myMap = Object.create(null)
myMp.name = "xxx"
let val = myMap.name
console.log(val)

ES 6  
Strong Set
let mySet = new Set()
mySet.add("xxx")
mySet.add("yyy")

let newSet = new Set([1,2,3,4,4,4])        // can casue memeory leak 
let chainSet = new Set().add("xxx").add("yyy")
console.log(newSet.has(4))
console.log(newSet.size)

Weak Set : store object reference
let set = new weakset() // set vs weakset, memory is handlel properly in the weak set

let myMap = new Map()
myMap.set("fname","eric")
console.log(myMap.get("fName"))

let obj1 = {}
let obj2 = {}
myMap.set(obj1,10)
myMap.set(obj2,20)
console.log(myMap.get(obj1))
console.log(myMap.delete(obj2))


for(let entry  of map.entries()){ // [key, val]
	// entry[0]
	
}

num.forEach(arrFunc)
function arrayFunction(element, index, array){
// ..............     for the map -> (val, key, callingMap)
}

Symbol

 let s = Sysmbol("xxxx")  // always create unique id

-----------------------------------------------------------------------Part One------------------------------------------------------------------
Browser Object global object, allows javascript to interact with the browser properties

window object
          window.open(url, name, size)
          window.close()
          window.moveTo(x,y)   open a new window and move to x,y location   
          window.resizeTo()
          
   localtion object : return current page URL, redirect to a new page
         location.href
         location.hostname 
         location..pathname  return the path and filename of current page
         location.protocol    return web protocol 
         location.assign       loads a new document
         
   history object: contains browser history
        history.back
        history.forward
   
   document object : a standard object model and programming interface for html, created by the browser, when a webpage 
                                is loaded, tree object
                                it defines HTML element as object, properties of all the HTML element , the methods to access all HTML
                                element and event for the the HTML element 
      form object
      image object
      link object
      
   navigator object : contains information of the visitor browser
        navigator.appName
        navigator.appCodeName
        navigator.platform   return OS name
        navigator.cookieEnabled
        navigator.product : return name of browser engine
        
   screen object
   		screen.width               return width of user screen
   		screen.height
   		screen.availWidth       return width of user screen, excluding all the side features like taskbar, sidebar etc.
   		screen.availHeight
   		screen.colorDepth      return the number of bits used to display one color
   		screen.pixelDepth      return the pixel depth of the screen

Document Object Model

     document object :  [Style, text, events]            [innerHTML, text, value] : access the content of the html element
          find element:  [getElementById(), getElementsByClassName(), getElementsByTagName()]  
          
          change style :    document.getElementById(uid).className = "other property"
          
          set attribute :     document.getELementById(uid).setAttribute("style","color:red")
          
          event
                   mouse event: mousedown, modeup, click , dblclick, mousemove, mouseover, mousewheel, mousewheel, mouseout, contextmenu
                   touch event : touchstart, touchmove, touchend, touchcancel
                   key event: keydown, keypress, keyup
                   form event: focus, blur, change, submit
                   window even: scroll, resize, hashchange, load, unload
                   
                               event listener :
                              let someFunc =  document.getElementByXX("param").addEventListener("click" , callBack function)
                              <input type="text" onclick="someFunc()"
          

Form validation :

  1. check if the input is empty
  2. check if the input is a numeric value
  3. check if the input is a valid email

------------------------------------------------------------Part Two ----------------------------------------------------------------------
对象

创建对象
		- 方式一:
			- var obj = new Object();
		- 方式二:
			- var obj = { attribute : property};
向对象中添加属性
		- 语法:
			对象.属性名 = 属性值;
			对象["属性名"] = 属性值;
读取对象中的属性
		- 语法:
			对象.属性名
			对象["属性名"]
删除对象中的属性
		- 语法:
			delete 对象.属性名
			delete 对象["属性名"]

使用in检查对象中是否含有指定属性
- 语法:"属性名" in 对象

This

This 用法
this的不同的情况:
		1.以函数的形式调用时,this是window
		2.以方法的形式调用时,this就是调用方法的对象
        3.以构造函数的形式调用时,this就是新创建的对象

函数

        函数也是一个对象,也具有普通对象的功能
          - 函数声明  
             //函数表达式,不会被提前创建
			function 函数名([形参1,形参2...形参N]){
				语句...
			}
		- 函数表达式  
		//函数表达式,  不会被提前创建
			var 函数名 = function([形参1,形参2...形参N]){
				语句...
			};
            var name = () => {
                              ……..
			}
		支持内部类
		function fun3(){
		          //在函数内部再声明一个函数
		                function fun4(){
		                    alert("我是fun4");
		                }
		                
		                //将fun4函数对象作为返回值返回
		                return fun4;
		            }
		            
		            a = fun3();
		            //console.log(a);
		            //a();
		            fun3()();
		立刻执行
		  ( fun xxx{}) ()
		
		Window. Fun() 
		Var c = "c "
    Window.c 

构造器

  function Person(name , age , gender){
                this.name = name;
                this.age = age;
                this.gender = gender;
                this.sayName = function(){
                    alert(this.name);
                };
            }
            var per = new Person("孙悟空",18,"男");
            var per2 = new Person("玉兔精",16,"女");
            var per3 = new Person("奔波霸",38,"男");

Prototype

全局 定义 
	• 看起来 像 static
//向原型中添加sayName方法
 Person.prototype.sayName = function(){
      alert("Hello大家好,我是:"+this.name);
 };
function Person(name , age , gender){
    this.name = name;
    this.age = age;
    this.gender = gender;
    //向对象中添加一个方法
    //this.sayName = fun;
}

我们所创建的每一个函数,解析器都会向函数中添加一个属性prototype

这个属性对应着一个对象,这个对象就是我们所谓的原型对象

他的 对象 实例 可以通过 __proto__ 来访问 这个公共域
对象本身 需要通过 prototype 来访问

console.log("name" in mc);  会访问到原型 中找 数据
用 hasOwnProperty() 来查 是否 元素本身 带者 属性,
语法:对象.hasOwnProperty

数组

.length 

	- var arr = new Array();
	- var arr = [];
	- 数组对象[索引] =-  var arr = [元素1,元素2....元素N];
	- Length
	- 修改数组的长度  arr.length = newLength
	- Push()
	- Pop()
	- Unshift()
	- Shift()
	- Slice(start, end)    subStr
	- Splice(start, amount, insert new element)
	- Reverse()
	- Concat() 链接 2 个数组
	- Join('中间加一个') 数组 转成 String
	- Sort()
            arr.sort(function(a,b){
                
                //前边的大
                /*if(a > b){
                    return -1; // 不变
                }else if(a < b){
                    return 1; // 换位置
                }else{
                    return 0; // 不变
                }*/
                
                //升序排列
                //return a - b;
                
                //降序排列
                return b - a;
                
            });
	
	call()
		- 改变call 中 this 的 方向
		- Bob.call(bill, 2, xxx)
	Apply() 
	  - 一样, 但是 他传的是 array
	  -  Bob.call(bill, [2,xxx])
	
    let fred = bob.Bind (bill, 2, xxx)  // prepare a return copy of call to fred 
For(;;){}
forEach( (val, index, objArr)=>{});


- arguments
		- arguments和this类似,都是函数中的隐含的参数
		- arguments是一个类数组元素,它用来封装函数执行过程中的实参
			所以即使不定义形参,也可以通过arguments来使用实参
		- arguments中有一个属性callee表示当前执行的函数对象

String, Date, Math,RegExp

包装类 
Number(), String(), Boolean()
	1. Length
	2. charAt
	3. charCodeAt
	4. fromCharCode
	5. indexOf
	6. lastIndexOf
	7. Slice(start, end)
	8. Substr(start, substred number)
	9. Substring(start, end) doesn't take negative number
	10. toLowerCase()
	11. toUpperCase()
	12. Split('xx')
	13. Match(reg)
	14. Replace( oldContent/reg, newContent)
	15. Search(reg)  : index
	
	
Date
getDate()
getDay()
getMonth()
getFullYear()
getTime()
Now()

Math
Abs()
Ceil()
Floor()
Round()
Random() * (y-x) + x    / * x          -> x ~ y    0 ~ x  
Min()
Max()
Pow()
Sqrt() 

正则表达式
var 变量 = new RegExp("正则表达式","匹配模式");

var reg = new RegExp("正则","匹配模式");
var reg = /正则表达式/匹配模式

Var result = reg.test(str)

	|[] 或     a|b == [ab]
	[^ ] 除了
	[a-z] 小写字母
	[A-Z] 大写字母
	[A-z] 任意字母
	[0-9] 任意数字


i:忽略大小写
g:全局匹配模式

 * 量词
 * 	- 量词只对它前边的一个内容起作用
 * 	- {n} 正好出现n次
 * 	- {m,n} 出现m-n次
 * 	- {m,} m次以上
 * 	- + 至少一个,相当于{1,}
 * 	- * 0个或多个,相当于{0,}
 * 	- ? 0个或1个,相当于{0,1}
 * 	^ 表示开头
 * 	$ 表示结尾

 * \w
 * 	- 任意字母、数字、_  [A-z0-9_]
 * \W
 * 	- 除了字母、数字、_  [^A-z0-9_]
 * \d
 * 	- 任意的数字 [0-9]
 * \D
 * 	- 除了数字 [^0-9]
 * \s
 * 	- 空格                                    | and   ()
 * \S
 * 	- 除了空格
 * \b
 * 	- 单词边界
 * \B
 * 	- 除了单词边界

 * \. 来表示.
 * \\  表示\

DOM

DOM查询
- document.getElementById("id属性值");
- document.getElementsByName("name属性值");
- document.getElementsByTagName("标签名");
	- document.querySelector()	选一个
	- document.querySelectorAll()   选一组
	


读取元素的属性:
	- Elem.id
	- Elem. value
	- Elem. className
修改元素的属性
	元素.属性名 = 属性值
	
innerHTML 
	使用该属性可以获取或设置元素内部的HTML代码
innerText
	和innerHTML差不多, 但是innerText 不会获取html 内容
	
- 元素.childNodes
	- 获取当前元素的所有子节点
	- 会获取到空白的文本子节点
- 元素.children
	- 获取当前元素的所有子元素
- 元素.firstChild
	- 获取当前元素的第一个子节点
- 元素.lastChild
	- 获取当前元素的最后一个子节点
- 元素.parentNode
	- 获取当前元素的父元素
- 元素.previousSibling
	- 获取当前元素的前一个兄弟节点
- 元素.nextSibling
- 获取当前元素的后一个兄弟节点

事件 
//获取按钮对象
//绑定一个单击事件

var btn = document.getElementById("btn");
btn.onclick = function(){
     alert("你还点~~~");
};


Window.onload = function(){
// 这个页面加载好后执行
	var btn = document.getElementById("btn");
	btn.onclick = function(){
	     alert("你还点~~~");
	};
	
}

事件对象
	封装了当前事件的相关信息

元素.事件 = function(event){
	event = event || window.event;
};


事件的冒泡(Bubble)

事件的冒泡指的是事件向上传导,当后代元素上的事件被触发时,将会导致其祖先元素上的同类事件也会触发

元素.事件 = function(event){
	event = event || window.event;
	event.cancelBuevent.cancel
};

2.DOM修改
	document.createElement()
		- 可以根据标签名创建一个元素节点对象
	document.createTextNode()
		- 可以根据文本内容创建一个文本节点对象
		
	父节点.appendChild(子节点)
		- 向父节点中添加指定的子节点
	父节点.insertBefore(新节点,旧节点)
		- 将一个新的节点插入到旧节点的前边
	父节点.replaceChild(新节点,旧节点)
		- 使用一个新的节点去替换旧节点
	父节点.removeChild(子节点)
		- 删除指定的子节点
		- 推荐方式:子节点.parentNode.removeChild(子节点)


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值