• Js基础知识5-函数返回值、函数参数、函数属性、函数方法


    函数返回值

    所有函数都有返回值,没有return语句时,默认返回内容为undefined,和其他面向对象的编程语言一样,return语句不会阻止finally子句的执行。

    function testFinnally(){
        try{
            return 2;
        }catch(error){
            return 1;
        }finally{
            return 0;
        }
    }
    testFinnally();//0

    如果函数调用时在前面加上了new前缀,且返回值不是一个对象,则返回this(该新对象)。

    function fn(){
        this.a = 2;
        return 1;
    }
    var test = new fn();
    console.log(test);//{a:2}
    console.log(test.constructor);//fn(){this.a = 2;return 1;}

    如果返回值是一个对象,则返回该对象。

    function fn(){
        this.a = 2;
        return {a:1};
    }
    var test = new fn();
    console.log(test);//{a:1}
    console.log(test.constructor);//Object() { [native code] }

    函数参数

    arguments

      javascript中的函数定义并未指定函数形参的类型,函数调用也未对传入的实参值做任何类型检查。实际上,javascript函数调用甚至不检查传入形参的个数。

    function add(x){
        return x+1;
    }
    console.log(add(1));//2
    console.log(add('1'));//'11'
    console.log(add());//NaN
    console.log(add(1,2));//2
    

    同名形参

      在非严格模式下,函数中可以出现同名形参,且只能访问最后出现的该名称的形参。

    function add(x,x,x){
        return x;
    }
    console.log(add(1,2,3));//3

         而在严格模式下,出现同名形参会抛出语法错误

    function add(x,x,x){
        'use strict';
        return x;
    }
    console.log(add(1,2,3));//SyntaxError: Duplicate parameter name not allowed in this context

    参数个数

      当实参比函数声明指定的形参个数要少,剩下的形参都将设置为undefined值

    function add(x,y){
        console.log(x,y);//1 undefined
    }
    add(1);

           常常使用逻辑或运算符给省略的参数设置一个合理的默认值

    function add(x,y){
        y = y || 2;
        console.log(x,y);//1 2
    }
    add(1);

      [注意]实际上,使用y || 2是不严谨的,显式地设置假值(undefined、null、false、0、-0、”、NaN)也会得到相同的结果。所以应该根据实际场景进行合理设置

      当实参比形参个数要多时,剩下的实参没有办法直接获得,需要使用即将提到的arguments对象

      javascript中的参数在内部用一个数组表示。函数接收到的始终都是这个数组,而不关心数组中包含哪些参数。在函数体内可以通过arguments对象来访问这个参数数组,从而获取传递给函数的每一个参数。arguments对象并不是Array的实例,它是一个类数组对象,可以使用方括号语法访问它的每一个元素

    function add(x){
        console.log(arguments[0],arguments[1],arguments[2])//1 2 3
        return x+1;
    }
    add(1,2,3);

          arguments对象的length属性显示实参的个数,函数的length属性显示形参的个数

    function add(x,y){
        console.log(arguments.length)//3
        return x+1;
    }
    add(1,2,3);
    console.log(add.length);//2

         形参只是提供便利,但不是必需的

    function add(){
        return arguments[0] + arguments[1];
    }
    console.log(add(1,2));//3

    对象参数

      当一个函数包含超过3个形参时,要记住调用函数中实参的正确顺序实在让人头疼

    function arraycopy(/*array*/from,/*index*/form_start,/*array*/to,/*index*/to_start,/*integer*/length){
        //todo
    }

          通过名/值对的形式来传入参数,这样参数的顺序就无关紧要了。定义函数的时候,传入的实参都写入一个单独的对象之中,在调用的时候传入一个对象,对象中的名/值对是真正需要的实参数据

    function easycopy(args){
        arraycopy(args.from,args.from_start || 0,args.to,args.to_start || 0, args.length);
    }
    var a = [1,2,3,4],b =[];
    easycopy({from:a,to:b,length:4});

    以函数为参数

          函数本身是一个对象,因此可以将函数作为另一个函数的参数,进而实现函数回调,功能等同于c++中的函数指针

    function printf(str){
        dom1.innerText += str.toString()+"
    ";              //设置dom1显示的文字。变量也可以自动调用其他js文件中的dom1变量。dom1会先在当前文件中查询,然后向之前引用的js文件查询,再向之后引用的js文件查询
    }
    
    function callfunction(myfunction,myargument){           //函数作为其他函数的参数
        return myfunction(myargument);                      //调用回调函数
    }
    
    callfunction(printf,"hello world");

    同步

      当形参与实参的个数相同时,arguments对象的值和对应形参的值保持同步

    function test(num1,num2){
        console.log(num1,arguments[0]);//1 1
        arguments[0] = 2;
        console.log(num1,arguments[0]);//2 2
        num1 = 10;
        console.log(num1,arguments[0]);//10 10
    }
    test(1);

      [注意]虽然命名参数和对应arguments对象的值相同,但并不是相同的命名空间。它们的命名空间是独立的,但值是同步的

      但在严格模式下,arguments对象的值和形参的值是独立的

    function test(num1,num2){
        'use strict';
        console.log(num1,arguments[0]);//1 1
        arguments[0] = 2;
        console.log(num1,arguments[0]);//1 2
        num1 = 10;
        console.log(num1,arguments[0]);//10 2
    }
    test(1);

          当形参并没有对应的实参时,arguments对象的值与形参的值并不对应

    function test(num1,num2){
        console.log(num1,arguments[0]);//undefined,undefined
        num1 = 10;
        arguments[0] = 5;
        console.log(num1,arguments[0]);//10,5
    }
    test();

    内部属性【callee】

      arguments对象有一个名为callee的属性,该属性是一个指针,指向拥有这个arguments对象的函数

      下面是经典的阶乘函数

    function factorial(num){
        if(num <=1){
            return 1;
        }else{
            return num* factorial(num-1);
        }
    }    
    console.log(factorial(5));//120

          但在严格模式下,访问这个属性会抛出TypeError错误

    function factorial(num){
        'use strict';
        if(num <=1){
            return 1;
        }else{
            return num* arguments.callee(num-1);
        }
    }    
    //TypeError: 'caller', 'callee', and 'arguments' properties may not be accessed on strict mode functions or the arguments objects for calls to them
    console.log(factorial(5));

         这时,可以使用具名的函数表达式

    var factorial = function fn(num){
        if(num <=1){
            return 1;
        }else{
            return num*fn(num-1);
        }
    };    
    console.log(factorial(5));//120

    【caller】

      实际上有两个caller属性

    【1】函数的caller

      函数的caller属性保存着调用当前函数的函数的引用,如果是在全局作用域中调用当前函数,它的值是null

    function outer(){
        inner();
    }
    function inner(){
        console.log(inner.caller);//outer(){inner();}
    }
    outer();
    function inner(){
        console.log(inner.caller);//null
    }
    inner();

         在严格模式下,访问这个属性会抛出TypeError错误

    function inner(){
        'use strict';
        //TypeError: 'caller' and 'arguments' are restricted function properties and cannot be accessed in this context
        console.log(inner.caller);
    }
    inner();

    【2】arguments对象的caller

      该属性始终是undefined,定义这个属性是为了分清arguments.caller和函数的caller属性

    function inner(x){
        console.log(arguments.caller);//undefined
    }
    inner(1);

          同样地,在严格模式下,访问这个属性会抛出TypeError错误

    function inner(x){
        'use strict';
        //TypeError: 'caller' and 'arguments' are restricted function properties and cannot be accessed in this context
        console.log(arguments.caller);
    }
    inner(1);

    函数重载

      javascript函数不能像传统意义上那样实现重载。而在其他语言中,可以为一个函数编写两个定义,只要这两个定义的签名(接受的参数的类型和数量)不同即可

      javascript函数没有签名,因为其参数是由包含0或多个值的数组来表示的。而没有函数签名,真正的重载是不可能做到的

    //后面的声明覆盖了前面的声明
    function addSomeNumber(num){
        return num + 100;
    }
    function addSomeNumber(num){
        return num + 200;
    }
    var result = addSomeNumber(100);//300

          只能通过检查传入函数中参数的类型和数量并作出不同的反应,来模仿方法的重载

    function doAdd(){
        if(arguments.length == 1){
            alert(arguments[0] + 10);
        }else if(arguments.length == 2){
            alert(arguments[0] + arguments[1]);
        }
    }
    doAdd(10);//20
    doAdd(30,20);//50

    参数传递

      javascript中所有函数的参数都是按值传递的。也就是说,把函数外部的值复制到函数内部的参数,就和把值从一个变量复制到另一个变量一样

    【1】基本类型值

      在向参数传递基本类型的值时,被传递的值会被复制给一个局部变量(命名参数或arguments对象的一个元素)

    function addTen(num){
        num += 10;
        return num;
    }
    var count = 20;
    var result = addTen(count);
    console.log(count);//20,没有变化
    console.log(result);//30

    【2】引用类型值

      在向参数传递引用类型的值时,会把这个值在内存中的地址复制给一个局部变量,因此这个局部变量的变化会反映在函数的外部

    function setName(obj){
        obj.name = 'test';
    }
    var person = new Object();
    setName(person);
    console.log(person.name);//'test'

         当在函数内部重写引用类型的形参时,这个变量引用的就是一个局部对象了。而这个局部对象会在函数执行完毕后立即被销毁

    function setName(obj){
        obj.name = 'test';
        console.log(person.name);//'test'
        obj = new Object();
        obj.name = 'white';
        console.log(person.name);//'test'
    }
    var person = new Object();
    setName(person);

    函数属性

    【length属性】

      arguments对象的length属性表示实参个数,而函数的length属性则表示形参个数

    function add(x,y){
        console.log(arguments.length)//3
        console.log(add.length);//2
    }
    add(1,2,3);

    【name属性】

      函数定义了一个非标准的name属性,通过这个属性可以访问到给定函数指定的名字,这个属性的值永远等于跟在function关键字后面的标识符,匿名函数的name属性为空

    //IE11-浏览器无效,均输出undefined
    //chrome在处理匿名函数的name属性时有问题,会显示函数表达式的名字
    function fn(){};
    console.log(fn.name);//'fn'
    var fn = function(){};
    console.log(fn.name);//'',在chrome浏览器中会显示'fn'
    var fn = function abc(){};
    console.log(fn.name);//'abc'

      [注意]name属性早就被浏览器广泛支持,但是直到ES6才将其写入了标准

      ES6对这个属性的行为做出了一些修改。如果将一个匿名函数赋值给一个变量,ES5的name属性,会返回空字符串,而ES6的name属性会返回实际的函数名

    var func1 = function () {};
    func1.name //ES5:  ""
    func1.name //ES6: "func1"

         如果将一个具名函数赋值给一个变量,则ES5和ES6的name属性都返回这个具名函数原本的名字

    var bar = function baz() {};
    bar.name //ES5: "baz"
    bar.name //ES6: "baz"

         Function构造函数返回的函数实例,name属性的值为“anonymous”

    (new Function).name // "anonymous"
    

      bind返回的函数,name属性值会加上“bound ”前缀 

    function foo() {};
    foo.bind({}).name // "bound foo"
    (function(){}).bind({}).name // "bound "
    

    【prototype属性】

      每一个函数都有一个prototype属性,这个属性指向一个对象的引用,这个对象称做原型对象(prototype object)。每一个函数都包含不同的原型对象。将函数用做构造函数时,新创建的对象会从原型对象上继承属性

    function fn(){};
    var obj = new fn;
    fn.prototype.a = 1;
    console.log(obj.a);//1
    

    函数方法

    【apply()和call()】

      每个函数都包含两个非继承而来的方法:apply()和call()。这两个方法的用途都是在特定的作用域中调用函数,实际上等于函数体内this对象的值

      要想以对象o的方法来调用函数f(),可以这样使用call()和apply()

    f.call(o);
    f.apply(o);
    

      假设o中不存在m方法,则等价于:

    o.m = f; //将f存储为o的临时方法
    o.m(); //调用它,不传入参数
    delete o.m; //将临时方法删除
    

      下面是一个实际的例子

    window.color = "red";
    var o = {color: "blue"};
    function sayColor(){
        console.log(this.color);
    }
    sayColor();            //red
    sayColor.call(this);   //red
    sayColor.call(window); //red
    sayColor.call(o);      //blue
    //sayColor.call(o)等价于:
    o.sayColor = sayColor;
    o.sayColor();   //blue
    delete o.sayColor;

          apply()方法接收两个参数:一个是在其中运行函数的作用域(或者可以说成是要调用函数的母对象,它是调用上下文,在函数体内通过this来获得对它的引用),另一个是参数数组。其中,第二个参数可以是Array的实例,也可以是arguments对象

    function sum(num1, num2){
        return num1 + num2;
    }
    //因为运行函数的作用域是全局作用域,所以this代表的是window对象
    function callSum1(num1, num2){
        return sum.apply(this, arguments);
    }
    function callSum2(num1, num2){
        return sum.apply(this, [num1, num2]);
    }
    console.log(callSum1(10,10));//20
    console.log(callSum2(10,10));//20

         call()方法与apply()方法的作用相同,它们的区别仅仅在于接收参数的方式不同。对于call()方法而言,第一个参数是this值没有变化,变化的是其余参数都直接传递给函数。换句话说,在使用call()方法时,传递给函数的参数必须逐个列举出来

    function sum(num1, num2){
        return num1 + num2;
    }
    function callSum(num1, num2){
        return sum.call(this, num1, num2);
    }
    console.log(callSum(10,10));   //20
    

      至于是使用apply()还是call(),完全取决于采取哪种函数传递参数的方式最方便。如果打算直接传入arguments对象,或者包含函数中先接收到的也是一个数组,那么使用apply()肯定更方便;否则,选择call()可能更合适

      在非严格模式下,使用函数的call()或apply()方法时,null或undefined值会被转换为全局对象。而在严格模式下,函数的this值始终是指定的值

    var color = 'red';
    function displayColor(){
        console.log(this.color);
    }
    displayColor.call(null);//red
    
    var color = 'red';
    function displayColor(){
        'use strict';
        console.log(this.color);
    }
    displayColor.call(null);//TypeError: Cannot read property 'color' of null
    

    应用

    【1】调用对象的原生方法

    var obj = {};
    obj.hasOwnProperty('toString');// false
    obj.hasOwnProperty = function (){
      return true;
    };
    obj.hasOwnProperty('toString');// true
    Object.prototype.hasOwnProperty.call(obj, 'toString');// false

    【2】找出数组最大元素

      javascript不提供找出数组最大元素的函数。结合使用apply方法和Math.max方法,就可以返回数组的最大元素

    var a = [10, 2, 4, 15, 9];
    Math.max.apply(null, a);//15

    【3】将类数组对象转换成真正的数组

    Array.prototype.slice.apply({0:1,length:1});//[1]
      或者
    
    [].prototype.slice.apply({0:1,length:1});//[1]

    【4】将一个数组的值push到另一个数组中

    var a = [];
    Array.prototype.push.apply(a,[1,2,3]);
    console.log(a);//[1,2,3]
    Array.prototype.push.apply(a,[2,3,4]);
    console.log(a);//[1,2,3,2,3,4]

    【5】绑定回调函数的对象

      由于apply方法(或者call方法)不仅绑定函数执行时所在的对象,还会立即执行函数,因此不得不把绑定语句写在一个函数体内。更简洁的写法是采用下面介绍的bind方法

    var o = {};
    o.f = function () {
      console.log(this === o);
    }
    var f = function (){
      o.f.apply(o);
    };
    $('#button').on('click', f);

    【bind()】

      bind()是ES5新增的方法,这个方法的主要作用就是将函数绑定到某个对象

      当在函数f()上调用bind()方法并传入一个对象o作为参数,这个方法将返回一个新的函数。以函数调用的方式调用新的函数将会把原始的函数f()当做o的方法来调用,传入新函数的任何实参都将传入原始函数

      [注意]IE8-浏览器不支持

    function f(y){
        return this.x + y; //这个是待绑定的函数
    }
    var o = {x:1};//将要绑定的对象
    var g = f.bind(o); //通过调用g(x)来调用o.f(x)
    g(2);//3

        兼容代码

    function bind(f,o){
        if(f.bind){
            return f.bind(o);
        }else{
            return function(){
                return f.apply(o,arguments);
            }
        }
    } 

        bind()方法不仅是将函数绑定到一个对象,它还附带一些其他应用:除了第一个实参之外,传入bind()的实参也会绑定到this,这个附带的应用是一种常见的函数式编程技术,有时也被称为’柯里化’(currying)

    var sum = function(x,y){
        return x+y;
    }
    var succ = sum.bind(null,1);
    succ(2); //3,x绑定到1,并传入2作为实参y
    function f(y,z){
        return this.x + y + z;
    }
    var g = f.bind({x:1},2);
    g(3); //6,this.x绑定到1,y绑定到2,z绑定到3
      使用bind()方法实现柯里化可以对函数参数进行拆分
    function getConfig(colors,size,otherOptions){
        console.log(colors,size,otherOptions);
    }
    var defaultConfig = getConfig.bind(null,'#c00','1024*768');
    defaultConfig('123');//'#c00 1024*768 123'
    defaultConfig('456');//'#c00 1024*768 456'

    【toString()】

      函数的toString()实例方法返回函数代码的字符串,而静态toString()方法返回一个类似’[native code]’的字符串作为函数体

    function test(){
        alert(1);//test
    }
    test.toString();/*"function test(){
                        alert(1);//test
                      }"*/
    Function.toString();//"function Function() { [native code] }"

    【toLocaleString()】

      函数的toLocaleString()方法和toString()方法返回的结果相同

    function test(){
        alert(1);//test
    }
    test.toLocaleString();/*"function test(){
                        alert(1);//test
                      }"*/
    Function.toLocaleString();//"function Function() { [native code] }"

    【valueOf()】

      函数的valueOf()方法返回函数本身

    function test(){
        alert(1);//test
    }
    test.valueOf();/*function test(){
                        alert(1);//test
                      }*/
    typeof test.valueOf();//'function'
    Function.valueOf();//Function() { [native code] }

     原链:https://blog.csdn.net/luanpeng825485697/article/details/77010261

  • 相关阅读:
    深入分析JavaWeb Item13 -- jsp指令具体解释
    Caused by: Unable to locate parent package [json-default] for [class com.you.user.action.StudentActi
    二分图学习整理
    mysql字段去重方式
    谈一谈我最喜欢的诗人--法国诗人波德莱尔
    玩转Web之html+CSS(一)---论坛首页表格的实现
    Windows 7旗舰版安装Visual Studio 2013 Ultimate的系统必备及注意事项
    android 去掉listview之间的黑线
    android 5.0新特性学习--RecyclerView
    ListView random IndexOutOfBoundsException on Froyo
  • 原文地址:https://www.cnblogs.com/7qin/p/9610407.html
Copyright © 2020-2023  润新知