JavaScript-函数和方法的区别

什么是函数

  • 函数就是没有和其它的类显示的绑定在一起的, 我们就称之为函数

什么是方法

  • 方法就是显示的和其它的类绑定在一起的, 我们就称之为方法

函数和方法的区别

  • 函数可以直接调用, 但是方法不能直接调用, 只能通过对象来调用
  • 函数内部的 this 输出的是 window, 方法内部的 this 输出的是当前调用的那个对象
  • 无论是函数还是方法, 内部都有一个叫做 this 的东东
  • this 是什么? 谁调用了当前的函数或者方法, 那么当前的 this 就是谁

如上的 this 分别由下面的两个示例来给你们演示一下,自行查看如下示例,第一个是函数,第二个是方法,至于为什么你查看我上面已经说明了,自行查看 #什么是函数#什么是方法 的概述。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Demo</title>
    <script type="text/javascript">
        function demo() {
            // console.log("hello demo");
            console.log(this);
        }

        // demo();
        window.demo();
    </script>
</head>
<body>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Demo</title>
    <script type="text/javascript">
        let obj = {
            name: "BNTang",
            test: function () {
                // console.log("hello test");
                console.log(this);
            }
        }

        // test();
        obj.test();
    </script>
</head>
<body>
</body>
</html>
posted @ 2021-07-22 13:36  BNTang  阅读(261)  评论(0编辑  收藏  举报