javascript_函数进阶_ZHOU125disorder_

函数进阶

函数定义

  • 函数的三种定义方法
  1. 函数声明定义
function 函数名(){
代码
}
  1. 函数表达式定义法
  • 匿名式函数表达式定义
var fn=function(){
代码
}
  • 命名式函数表达式定义法
var fn=function content(){
代码
}
  1. 构造函数定义法
    构造函数首字母大写不成文的规定
var fn=new Function("a1","a2","alert(a1*a2)")
fn(13,14);				//182
    // 函数声明定义
    // function fn(){}
    // 可以先调用再声明
    // 声明提升


    // 函数表达式定义不存在声明提升的
    // fn();        //报错
    // var fn = function(){
    //     alert("卡卡西");
    // }

函数调用

  1. 函数模式调用 函数名();
        // 1. 函数模式调用
        var content="我的名字叫卡卡西";
        function value(x){
            console.log(x);							//我的名字叫卡卡西
            console.log(this);						//window		函数模式调用的时候,this就是window
            console.log(this.content);		//我的名字叫卡卡西
        }
        value(content);
  1. 方法模式调用 当函数体在对象里面 .方法()
        var content="我的名字叫卡卡西";
        var obj={
            "content":"我的名字加我爱罗",
            "word":"我的愿望是成为火影",
            "value":function fn(){
                console.log("卡卡西");					//卡卡西
                console.log(this);							//obj
                console.log(this.content);   			//我的名字叫我爱罗		方法模式调用里面,this就是调用者
                console.log(content);					//我的名字叫卡卡西
            }
        }
        obj.value();

面试题

        //面试题
        var content00={
            "value":"我的名字叫卡卡西",
            "obj":function(){
                var content01={
                    "value":"我的名字叫卡卡西",
                    "obj":function(){
                        console.log(this.value);
                    }
                }
                content01.obj();
            }
        }
        content00.obj();

call和apply调用(主要在面向对象中使用)

    <style>
        *{
            margin: 0px;
            padding: 0px;
            list-style: none;
        }
        div{
            width: 256px;
            height: 256px;
            margin: 49px auto;
        }
    </style>

    <script>
        var div=document.getElementsByTagName("div")[0];
        function color(attr,value){
            //attr为属性    value为值
            this.style[attr]=value;
        }
        window.color.call(div,"background","#096");
     // 因为window里面没有style属性,所以,需要改变一下this指向
    </script>

call和apply的方法改变this的指向

cellapply的区别

  • cell和apply的能力是一样的

cellapply的区别

  • cell(content,"卡卡西","我爱罗")
  • apply(content,["卡卡西","我爱罗"])
    写法不一样

猜你喜欢

转载自blog.csdn.net/ZHOU125disorder/article/details/113175587