zoukankan      html  css  js  c++  java
  • 回归JavaScript基础(七)

    主题:引用类型Function的介绍。

     

    今天首先说的就是Function类型。下面就是定义函数的两种方法,第一种使用函数声明语法定义,第二种使用函数表达式定义。这两种定义函数的方式几乎没有什么区别。

    1 function func1() {}
    2 var func2 = function() {}
    3 console.log(typeof(func1)); //function
    4 console.log(typeof(func2)); //function

    非要说区别就如下面代码所示。在执行JavaScript前会对申明的变量和函数进行提前,把这些都自动放到执行代码的最上方,但是变量的赋值却不提升!是不是很费解,不过这就是JavaScript的规定,一定要注意!

    1 console.log(hello());  //"Hello,world."
    2 console.log(hi());     //undefinded
    3 function hello() {
    4     return "Hello,world.";
    5 }
    6 var hi = function() {
    7     return "Hi,world.";
    8 };

    函数源于对象,因此实际上函数名实际上也是一个指向函数对象的指针。下面代码中的hello和hi就是指向同一个function对象。

    1 function hello() {
    2     return "Hello,world!";
    3 }
    4 hello();  //"Hello,world!"
    5 var hi = hello; //注意:不带括号的函数名访问的是函数指针
    6 hi();  //"Hello,world!"

    在前面就提过,JavaScript中函数没有重载。这里,我们可以通过函数表达式的例子更清楚了解这点。

    1 var add = function(num) {
    2     return num + 1;
    3 };
    4 add = function(num) {
    5     return num + 2;
    6 };
    7 var result = add(1);    //3 
    8 //备注:很明显,第二次的function覆盖了第一次function

    函数可以作为一个值再传给另一个函数。

    1 function addFunc(func, arg) {
    2     return func(arg);
    3 }
    4 var add = function(num) {
    5     return num + 1;
    6 };
    7 var result = addFunc(add, 1);
    8 console.log(result);    //2

    (拓展)函数的apple()和call()方法。有兴趣可以查查资料,后面还会介绍!

    1 var name = "xuchaoi";
    2 var blog = {name: "blog.xuchaoi"};
    3 function getName() {
    4     console.log(this.name);
    5 }
    6 getName();              //xuchaoi
    7 getName.apple(blog);    //blog.xuchaoi
    8 getName.call(blog);     //blog.xuchaoi
  • 相关阅读:
    nginx路径详解
    负载均衡
    http中消息头的安全配置及工作原理
    Tomcat的ErrorPage实现原理分析及阀门ErrorReportValve
    Tomcat中Logger组件
    NIO在Tomcat中的应用
    vue中强制生效css样式
    k8s中的Ingress
    xhr.withCredentials与 CORS 什么关系
    Redis Cluster集群
  • 原文地址:https://www.cnblogs.com/xuchaoi/p/7128866.html
Copyright © 2011-2022 走看看