JavaScript-prototype特点

prototype 特点

  • 存储在 prototype 中的方法可以被对应构造函数创建出来的所有对象共享
  • prototype 中除了可以存储方法以外, 还可以存储属性
  • prototype 中如果出现了和构造函数中同名的属性或者方法, 对象在访问的时候, 访问到的是构造函中的数据

prototype 应用场景

  • prototype 中一般情况下用于存储所有对象都相同的一些属性以及方法
  • 如果是对象特有的属性或者方法, 我们会存储到构造函数中
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Demo</title>
    <script type="text/javascript">
        function Person(name, age) {
            this.name = name;
            this.age = age;
            this.currentType = "构造函数中的 currentType";
            this.say = function () {
                console.log("构造函数中的 say");
            }
        }

        Person.prototype = {
            currentType: "人",
            say: function () {
                console.log("hello world");
            }
        }
        
        let objOne = new Person("tyh", 34);
        let objTwo = new Person("zs", 44);

        objOne.say();
        objTwo.say();

        console.log(objOne.currentType);
        console.log(objTwo.currentType);
    </script>
</head>
<body>
</body>
</html>
posted @ 2021-07-22 17:51  BNTang  阅读(38)  评论(0编辑  收藏  举报