码迷,mamicode.com
首页 > 编程语言 > 详细

javascript高级课程-4

时间:2019-08-22 18:59:21      阅读:68      评论:0      收藏:0      [点我收藏+]

标签:cat   code   round   cal   java   apply   prototype   document   name   

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

技术图片

 

javascript高级课程-4

标签:cat   code   round   cal   java   apply   prototype   document   name   

原文地址:https://www.cnblogs.com/webcyh/p/11395820.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!