call、apply

var test1 = document.getElementById("test1");
    var test2 = document.getElementById("test2");
    function t(){
        console.log(arguments);
        this.style.background = 'gray';
    }

    t.call(test1,1,2,1,2);
    /*
    函数名.call(对象,参数)
    1、把函数的this指向对象
    2、运行函数,传递参数
    //apply的参数是传递数组
    */

闭包

    /*作用域在声明时候已经决定了*/
    var cnt=(function t(){
        var age = 21;//局部变量 不会污染全局变量
        return function(){//只有该函数可以访问局部变量
            return age++;
        }
    })();
    
    //防止函数污染
    var $ = {};
    $.cnt=cnt;
    console.log($.cnt());
    console.log($.cnt());
    console.log($.cnt());
    console.log($.cnt());

私有属性

function Girl(name,age){
        var name=name;//局部变量
        var age=age;
        this.getlove=function(){
            return name;
        }
    }

    var g = new Girl("test",21);//通过闭包完成私有属性封装
    console.log(g.getlove()); //只能通过g的getlove属性获取局部变量

原型

function Cat(){
        this.climb =function(){
            console.log("爬行");
        }
    }
    function Tiger(){
        this.hunt=function(){
            console.log("打猎");
        }
    }
    Tiger.prototype = new Cat();
    Tiger.prototype.song=function(){
        //扩充原型行为
        console.log("唱歌");
    }
    var t = new Tiger();
    //给 所有 对象添加这个行为
    Object.prototype.say=function(){
        console.log("hehe");
    }
    var d = new Date();
    d.say();//日期对象都有这个行为因为日期对象的最终原型也是Object



    t.hunt();
    t.climb();
    t.song();
    //console.log(new Cat());
    //console.log(Tiger.prototype);
    console.log(t.__proto__);//原型是猫对象
    console.log(t.__proto__.__proto__);//原型是空对象
    console.log(t.__proto__.__proto__.__proto__);//原型是最原始的对象
    console.log(t.__proto__.__proto__.__proto__.__proto__);//原型为null

 原型冒充(相当于继承过来)

function Good(){
        this.iq=120;
    }
    function Bad(){
        Good.call(this);
        this.show  =function(){
            console.log(this.iq);
        }
    }
    var b = new Bad();
    b.show();

结果:

复制继承

function Good(){
        this.iq=120;
    }
    function Bad(){
        Good.call(this);
        this.show  =function(){
            console.log(this.iq);
        }
    }
    function Test(){
        this.extend=function(obj){
            for(var key in obj){
                this[key] = obj[key];
            }
        }
    }
    var b = new Bad();
    var t = new Test();
    t.extend(b);
    console.log(t);
    b.show();

函数本身也是对象

函数.length为参数个数

函数.name函数名称

posted on 2019-08-22 17:44  渐凸强、啊哈  阅读(216)  评论(0)    收藏  举报