Javascript高级程序设计

JavaScript高级程序设计

  • 变量,作用域和内存问题
    • object类型值的引用赋值

       var obj1 = new Object();
       var obj2 = obj1;
       obj1.name = 'za'
       //obj2.name = za
      
    • 函数参数全部都是值传递

    • typeof|instanceof

       typeof(a);
       a instanceof b;
      
    • JS没有块级作用域(所以if或者for中的变量可以在之后继续调用)

    • 局部变量的优先级高于全局变量的优先级

    • 作用域(scope)和作用域链(scope chain)

    • 自动垃圾回收机制(标记清除类型 | 引用计数)

    • 设置对象的值为null来手动解除引用

  • 引用类型
    • 大部分引用类型是Object的

       var a = {a:b,c:d}
      
    • Array

      • array.length
      • isArray
      • toString,valueOf,toLocalString,join('#')
      • 直接使用pushpop将array变成栈类型
      • 使用pushshift变成队列类型,unshift向前端推入任意项的数据
      • sort(function<排序规则>)reverse()
      • array.concat(array1,array2)合并数组
      • array.slice(beginSynax,endSynax)选取某几个创建数组
      • array.splice(begin,number,array)替换
      • array.indexOf() | array.lastIndexOf()查找
      • 迭代方法
        • every():
        • filter()
        • foeEach()
        • map()
        • some()
      • 归并方法
        • reduce()

        • reduceRight()

           var values = [1,2,3,4,5];
           var sum = values.reduce(function(prev, cur, index, array){
           return prev + cur;
           });
           alert(sum); //15
          
    • Date类型

      • Date.parse()返回毫秒数

         Date.parse('Wed, 09 Aug 1995 00:00:00 GMT')
        
      • Date.UTC(year, month[, day[, hour[, minute[, second[, millisecond]]]]])

         var utcDate = new Date(Date.UTC(96, 11, 1, 0, 0, 0));
        
  • RegExp类型(正则表达式的支持)
    • var expression = / pattern / flags(g|i|m);
  • function
    • 函数声明早于函数执行

    • this 和 arguments.callee(指向函数本身,arguments为传入的参数)

       function factorial(num){
       if (num <=1) {
         return 1;
         } else {
             return num * arguments.callee(num-1)
           }
       }
      
    • javascript中的三种类型的方法

      • 对象方法:声明在函数体内部的
      • 类方法:使用函数名+.+方法名声明的
      • 原型方法:使用函数名+.+prototype+.+方法名声明的
    • length(函数希望得到的参数个数) 和 prototype

      • prototype->
      • prototype不能枚举
      • 增加一个既有对象的方法object.prototype.functionName = ()=>{}
      • 函数原有的方法无法使用prototype进行修改
    • function和作用域的绑定

      • function.apply(作用域,参数列表(array/arguments))
      • function.call(作用域,argument1,argument2...)
      • function.bind(object):绑定作用域到function中,即传this到function中
    • Boolean,Number,String引用类型

      • String ->

      • 查找String特定位置的字符:String.charAt(1) | String.charCodeAt(1) | String[1]

      • 字符串操作:concat() | slice() | substr() | substring()

      • 字符串位置:indexOf() | lastIndexOf() |

      • 字符串分割:trim()

      • 大小写转换:toLowerCase() | toLocalLowerCase() | toUpperCase() | toLocalUpperCase()

      • 字符串模式匹配:match() | RegExp.exec() | search() | replace()

         var text = "cat, bat, sat, fat";
         var pattern = /.at/;
         //与pattern.exec(text)相同
         var matches = text.match(pattern);
         alert(matches.index); //0
         alert(matches[0]); //"cat"
         alert(pattern.lastIndex); //0
        
      • localeCompare()

      • fromCharCode():将若干个编码转化成字符串

    • 单体内置对象(Global和Math)

      • Global->
      • URI编码方法:encodeURI() <==> decodeURI() | encodeUIRCompoent() <==> decodeURIComponent()
      • eval()
      • window
      • Math->
      • min() | max() | ceil(向上) | floor(向下) | round(标准)
  • 面向对象
    • 数据属性

      • 修改Object.defineProperty(object,'object.attribution',{writable:false ...})
    • 访问器属性(getter和setter)

    • 私有成员变量:_attribution

    • defineproperties()

       Object.defineProperties(object,
         'object.attribution':value,
         'object.attribution':{
           get:()=>{}
         }
       )
      
    • 定义对象的getter和setter方法

       object.__defineGetter__('object.attribution',()=>{return value})
       object.__defineSetter__('object.attribution',()=>{return value})
      
    • 读取属性的特性:Object.getOwnPropertyDescriptor(object,object.attribution)

    • 创建对象:

      • 工厂模式:

         function createPerson(name, age, job){
         var o = new Object();
         o.name = name;
         o.age = age;
         o.job = job;
         o.sayName = function(){
         alert(this.name);
         };
         return o;
         }
         var person1 = createPerson("Nicholas", 29, "Software Engineer");
         var person2 = createPerson("Greg", 27, "Doctor");
        
      • 构造方法(首字母大写,没有返回值)

         function Person(name, age, job){
         this.name = name;
         this.age = age;
         this.job = job;
         this.sayName = sayName;
         }
         function sayName(){
         alert(this.name);
         }
         var person1 = new Person("Nicholas", 29, "Software Engineer");
         var person2 = new Person("Greg", 27, "Doctor");
        
      • 原型模式(prototype)

         function Person(){
         }
         Person.prototype.name = "Nicholas";
         Person.prototype.age = 29;
         Person.prototype.job = "Software Engineer";
         Person.prototype.sayName = function(){
         alert(this.name);
         };
         var person1 = new Person();
         person1.sayName(); //"Nicholas"
        
prototype.png
   - `Person.prototype.isPrototypeOf(person1)` | `Object.getPrototypeOf(person1).name`
   - 原型更新马上能体现在实例上(动态性),但是重写原型会导致之前的实例报错
   - 组合使用原型和构造函数

          function Person(name, age, job){
            this.name = name;
            this.age = age;
            this.job = job;
            this.friends = ["Shelby", "Court"];
          }
          Person.prototype = {
            constructor : Person,
            sayName : function(){
            alert(this.name);
            }
          }
  • 继承
    • 原型链
      • SubType继承了SuperType的prototype

        function SuperType(){
        this.property = true;
        }
        SuperType.prototype.getSuperValue = function(){
        return this.property;
        };
        function SubType(){
        this.subproperty = false;
        }
        //继承了SuperType
        SubType.prototype = new SuperType();
        SubType.prototype.getSubValue = function (){
        return this.subproperty;
        };
        var instance = new SubType();
        alert(instance.getSuperValue()); //true

prototype_chain.png
- 所有的原型都继承于object
  • BOM(browser object model)
    • window对象
      • 超时调用和间歇调用
        • 超时调用 setTimeout | clearTimeout
        • 间歇调用 setInterval | clearInterval
      • 系统对话框
        • alert()

        • confirm()

           if(confirm('Are you sure?')){
             alert('sure');
           }else{
             alert('false');
           }
          
        • prompt('提示','默认值')

           let result = prompt('What's your name?','');
           result = null;
          
    • location对象
      • 属性:


        locationAttribution.png
      • 查询字符串location.search

      • 位置操作location.assign

    • navigator对象(用于识别浏览器对象)
      • 检测插件navigator.plugins
      • 注册处理程序navigator.registerContentHandler | navigator.registerProtocolHandler
    • screen对象
    • history对象
  • DOM
    • 5个常用的DOM方法:

      • getElementById
      • getElementByTagName
      • getElementByClassName
      • setAttribute(value,new_value)&&element.value = new_value
      • getAttribute
    • element.childNodes

      • nodeType
      • nodeName
      • firstChild
      • lastChild
      • length
    • html中的12种节点

      • element_node(就是标签)
      • attribute_node(标签中的属性)
      • text_note(文本内容) ...
    • nodeValue

    • 平稳退化

      • window.open(url,name,features)
      • javascript伪协议javascript:
      • 渐进增强
      • css
    • 分离js

      • window.onload = function(),在所有的html加载完以后再执行
    • 向后兼容性

    • 性能考虑

    • JSMin | YUI Compressor | Closure Compiler

    • addLoadEvent(用于执行window.onload的多个function)

       function addLoadEvent(func){
           var old_on_load = window.onload;
           if(typeof window.onload!='function'){
               window.onload = func;
           }else{
               window.onload = function(){
                   old_on_load();
                   func();
               }
           }
       }
      
    • onkeypress监听键盘

    • HTML-DOM和DOM-core

    • 动态创建标签

      • document.write
      • innerHTML
      • creatElement 创建元素
      • createTextNode 创建文本节点
      • appendChild append to the end of parentNode
      • insertBefore
        • parentNode
        • lastChild
        • appendChild
        • insertBefore
        • nextSibling
      • element.style.color
      • 伪类 a:hover
      • 通过使用className来进行element.className
      • element.addClass
    • setTimeout("function",interval)

    • praseInt(type string)

    • Modernizr库对于HTML5和CSS的改变

  • 客户端检测
  • 事件
    • 事件冒泡
    • 事件捕获
  • note
    • babel可以将es5的代码转化成es6

      • 先将es6转化成ast(抽象语法树)
      • 根据指定的presets(规则集)转化成对应的语法
      • 支持JSX
    • <script>:defer

    • <noscript>:在js不被支持或者被禁用的情况下调用

    • ES5严格模式:

    • 在脚本顶部添加"use strict"

    • 所有变量都要显式地使用var声明

    • 编译时确定属性和方法属于谁

      • 禁止使用with

         with(){
           var name = '1';
         }
        
      • eval作用域

      • 禁止删除变量

    • 显式报错(当给只读属性进行赋值时|没有八进制|...)

    • 安全措施:

      • 禁止this关键字指向全局变量

      • 禁止函数内部遍历调用栈

        function f1(){
          "use strict"
          f1.caller;//报错,指向当前函数
          f1.argument;//报错,指向传入的参数
        }
        
    • 不能有重名的参数和属性

    • 禁止八进制表示法

    • arguments对象限制

      • 不允许对arguments进行赋值
      • arguments不再追踪参数的变化
      • 禁用arguments.callee
    • 函数必须声明在顶层

    • 保留字增加

    • let和const(var表示局部变量,不加var表示全局变量)

      function(){
        var name;//局部变量
      }
      funciton(){
        name = 'jack';//全局变量
      }
      
    • ECMAScript中typeof返回的类型值:

      • undifined:未定义
      • boolean:bool型
        • 使用Boolean()函数转化值
typeof.png
    - `string`:字符串
    - `number`:数字
      - `NaN`:返回值需要是一个number时,并没有返回number
      - `isNaN()`:`valueOf()`->`toString`
    - `object`:对象或者null
    - `function`:函数
 - document.all():页面所有元素
 - .focus():光标聚焦
 - 表单提交验证

          <html>
               <head>
               <script type="text/javascript">

               function validate_required(field,alerttxt)
               {
               with (field)
                 {
                 if (value==null||value=="")
                   {alert(alerttxt);return false}
                 else {return true}
                 }
               }

               function validate_form(thisform)
               {
               with (thisform)
                 {
                 if (validate_required(email,"Email must be filled out!")==false)
                   {email.focus();return false}
                 }
               }
               </script>
               </head>

               <body>
               <form action="submitpage.html" onsubmit="return validate_form(this)" method="post">
               Email: <input type="text" name="email" size="30">
               <input type="submit" value="Submit">
               </form>
               </body>

               </html>
 - `addEventListener`:为指定元素添加事件

           <script>
           document.getElementById('Button').addEventListener(
             'click',function(){
             document.getElementById('demo').innerHTML='Hello World'
             })
           </script>

 - `removeEventListener`:移除元素的事件

           document.removeEventListener(
             document.getElementById('Button',function1))
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 198,932评论 5 466
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 83,554评论 2 375
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 145,894评论 0 328
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 53,442评论 1 268
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 62,347评论 5 359
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 47,899评论 1 275
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,325评论 3 390
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,980评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,196评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,163评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,085评论 1 328
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,826评论 3 316
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,389评论 3 302
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,501评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,753评论 1 255
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,171评论 2 344
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 41,616评论 2 339

推荐阅读更多精彩内容