JavaScript语言精粹代码总结

 /*对象索引*/
    {
        let obj = { name : 'xiaoming', sex:'man'};
        Object.create = (o)=>{
          let F = function () {};
          F.prototype = o;
          return new F();
        };
        let anoter = Object.create(obj);
        console.log(typeof anoter.name);//可以索引到原型链  string
        console.log(obj.hasOwnProperty('name'),anoter.hasOwnProperty('name'));//只索引本身含有的值; true false

        /*for in枚举*/
        for(item in anoter)
        {
            console.log(item);//会枚举出原型带有的属性
        }
        /*删除对象属性*/
        anoter.name='xiobai';
        console.log(anoter.name);//xiaohong
        delete anoter.name;
        console.log(anoter.name);//删除属性后暴露原型带有的属性  xiaoming
    }

    /*减少全局污染*/
    {
        var MYAPP={};
        MYAPP.stooge={/*最小化全局污染是为你的应用创建唯一一个全局变量*/}
    }
    /*js的四种调用模式(决定this的值):1.方法调用2.函数调用3.构造器调用4.apply调用*/
    /*方法调用*/
    {
        let obj={
            a:1,
            b:function(c){
                return this.a+c;
            }
        };
        console.log(obj.b(3));
    }
    /*函数调用模式*/
    {
        let obj={value:1};
        obj.double=function () {
            let that = this;
            let helper = function () {
                that.value= that.value+that.value;   //函数调用this会被绑定到全局对象
            };
            helper();
        };
        obj.double();
        console.log(obj.value);
        /*补充:箭头函数修正*/
        obj.double2=function () {
            let helper =  ()=> {
                this.value= this.value+this.value;   //this修正
            };
            helper();
        };
        obj.double2();
        console.log(obj.value);
    }
    /*构造器调用*/
    {
        let Quo = function (name) {
            this.name = name;
        };
        Quo.prototype.get_name= function () {
            return this.name;
        };
        let one = new Quo('小明');  //new调用时,背地创建一个连接该函数的prototype成员的新对象,this则绑定到该对象上
        console.log(one.get_name());
    }

    /*Apply调用模式(传递一个数组)*/
    {
        function add(a,b){
            return a+b;
        }
        let arr=[5,6];
        console.log(add.apply(null,arr));  //某种方法赋予到指定对象说,另外call用法相同但传参为列举而非数组
    }

    /*异常处理*/
    {
        let sum = function (a,b) {
            if(typeof a !== 'number' || typeof b !== 'number'){
                throw {                                      //抛出异常对象
                    name:'TypeError',
                    message:'a or b much be number'
                }
            }
            return a+b;
        };
        try{
            sum('abc',7)
        }catch (e) {
            console.log(e);
        }
    }
    /*递归 个人举例:快速排序法*/
    {
        let sort=(arr,left = 0,right = arr.length-1)=>{
            /*关键*/
            if(left >= right){
                return arr
            }
            //去最后一个数为基准数
            let val = arr[right];
            //遍历判断
            let i=left;
            let j=right;
            while(i<j){
                // 从前往后,比基数大则调换位置
                while(arr[i]<val){
                    i++
                }
                arr[j] = arr[i];
                //从后往前,比基数小则调换位置
                while(arr[j]>val){
                    j--
                }
                arr[i] =  arr[j];
            }
            //此时 i===j
            arr[i] = val;
            sort(arr,0,i-1);
            sort(arr,i+1,right);
            return arr;
        };
        console.log(sort([0,56,98,12,65,31]));
    }
    /*作用域*/
    //书中JavaScript不支持块级作用域
    //补充:ES6中最新的变量什么 let和const使得块级作用域得到修正,在{}内部仍然可以作为块级作用域

    /*闭包*/
    {
        var fade = function (node) {
            var level = 1;
            var step = function () {
                var hex = level.toString(16);
                node.style.backgroundColor = '#FFFF'+hex+hex;  //使用外部变量node
                if(level<15)
                {
                    level += 1;
                    setTimeout(step,100);      //再次执行step,step内部函数的外部变量level为此时的level值,所以level可以逐渐递增
                }
            };
            setTimeout(step,100);
        };

        fade(document.body); //调用一次后fade函数已经返回,但由于内部函数的需要,外部变量仍然会继续保留
    }
    {
        function func() {
            let result = [];
            let result2 = [];
            let result3 = [];
            for (var i = 0; i < 10; i++) {
                result[i] = function () {
                    return i;
                };
                result2[i] = function(num){
                    return function () {
                        return num;
                    }
                }(i);
            }
            for(let j = 0;j<10;j++){
                result3[j] = function () {
                    return j;
                };
            }
            console.log(result[5]());  //由于函数的调用在此处,for语句无块级作用域导致返回值和预想的不一样,此时外部变量经过for循环后为10,所以结果均为10
            console.log(result2[5]());  //解决方法一 : 用匿名函数添加一个闭环境传入值
            console.log(result3[5]());  //解决方法二 : 用ES6语法中let生命变量,是for循环也可以拥有块级作用域
        }
        func();
    }

    /*模块*/
    {} //es6
    (function(){}()) //传统闭包模块 :一个定义了私有变量和函数的函数,利用闭包创建可以访问私有变量和函数的特权函数;最后返回这个特权函数或者保存到一个可访问的地方

    /*级联*/
    //如果让方法的返回值为this而不是undefined,则可以通过级联的方式调用同意个对象的很多方法
    {
        let obj={
            name:'ss',
            age:18,
            getName() {
                console.log(this.name);
                return this;
            },
            getAge(){
                console.log(this.age);
                return this;
            }
        };
        obj.getName().getAge();
    }

    /*记忆*/
    //通过数组或者其他形式存储结算结果,避免重复不必要的计算

    /*继承*/
    {
        function People(name,age){
            this.name = name;
            this.age = age;
        }
        People.prototype.get_name= function(){
            return this.name;
        };
        let person1= new People('xiaoming',5);
        function Person(name,age) {
            this.name = name;
            this.age = age;
        }
        Person.prototype= new People();  //继承People类
        Person.prototype.get_age= function(){ //扩充原型方法
            return this.age;
    };
        let person2 = new Person('小红',5);
        console.log(person2.get_name());
        console.log(person2.get_age());
    }
    /*es6 class语法糖继承对比*/
    {
        class People {
            /*构造器*/
            constructor(name,age){
                this.name=name;
                this.age = age;
            }
            //方法
            get_name(){
                return this.name;
            }
        }
        let person1= new People('xiaoming',5);
        console.log(person1.get_name());
        //开始继承
        class Person extends People{
            constructor(name,age){
            super(name,age);//必须调用super方法
            }
            get_msg(){
                return super.get_name()+' 年龄:'+this.age.toString(); //调用父类的方法
            }
        }
        let person2=new Person('小红',80);
        console.log(person2.get_msg());
        console.log(person2.get_name()); //继承方法成功
    }

    /*数组的删除*/
    {
        let arr = ['a','b','c','d'];
        delete  arr[2];
        console.log(arr);
        arr = ['a','b','c','d'];
        arr.splice(2,2,'e','f','g');
        console.log(arr);
    }
    /*正则表达式*/
    {
        let reg = /^(?:([A-Za-z]+):)?(\/{0,3})([0-9.\-A-Za-z]+)(?::(\d+))?(?:\/([^?#]*))?(?:\?([^#]*))?(?:#(.*))?$/;
        let result = reg.exec('http://www.baidu.com:80/goodparts?q#fragement');
        console.log(result);
        console.log(reg.test('http://www.baidu.com:80/goodparts?q#fragement'));
        console.log(reg.test('http:www.baidu.com:80/goodparts?q#fragement'))
    }

    /*sort方法*/
    {
        let arr=[12,56,12,56,3,2,15,8,21,32,655,452,'a','aa','bbb'];
        console.log(arr.sort(function(a,b){
            return a-b;
        }))
    }
    /*Number.toFixed*/
    {
        let pi = Math.PI;
        console.log(pi,pi.toFixed(2),pi.toFixed(15))
        /*toString*/
        console.log(pi.toString(2));
    }

    /*毒瘤之自动插入分号*/
    {
        function func(){
            return    //这里自动插入分号导致返回undefined
            {
                a:'ad'
            };
        }
        console.log(func());
    }

    /*毒瘤之浮点数*/
    {
        console.log(0.1+0.2,parseInt(0.1+0.2))
    }
    /*毒瘤之Nan*/
    {
        console.log(typeof NaN,NaN===NaN,isNaN('oops'));
        let arr = [];
    }
    /*毒瘤之function语句*/
    {
        a();
        function a(){     //函数声明提升
            console.log("a is running")
        }
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值