JavaScript-原型链

  • 对象中 __proto__ 组成的链条我们称之为原型链

image-20210904150205825

  • 对象在查找属性和方法的时候,会先在当前对象查找
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>JavaScript-原型链</title>
    <script>
        function Person(name, age) {
            this.name = name;
            this.age = age;
            this.currentType = "构造函数中的type";
            this.say = function () {
                console.log("构造函数中的say");
            }
        }

        Person.prototype = {
            // 注意点: 为了不破坏原有的关系, 在给prototype赋值的时候, 需要在自定义的对象中手动的添加constructor属性, 手动的指定需要指向谁
            constructor: Person,
            currentType: "人",
            say: function () {
                console.log("hello world");
            }
        }
        let obj = new Person("BNTang", 34);
        console.log(obj.currentType);
        obj.say();
    </script>
</head>
<body>
</body>
</html>

image-20210904150537926

  • 如果当前对象中找不到想要的,会依次去上一级原型对象中查找
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>JavaScript-原型链</title>
    <script>
        function Person(name, age) {
            this.name = name;
            this.age = age;
        }

        Person.prototype = {
            constructor: Person,
            currentType: "人",
            say: function () {
                console.log("hello world");
            }
        }
        let obj = new Person("BNTang", 34);
        console.log(obj.currentType);
        obj.say();
    </script>
</head>
<body>
</body>
</html>

image-20210904150517125

  • 如果找到 Object 原型对象都没有找到,就会报错
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>JavaScript-原型链</title>
    <script>
        function Person(name, age) {
            this.name = name;
            this.age = age;
        }

        Person.prototype = {
            constructor: Person
        }
        let obj = new Person("BNTang", 34);
        console.log(obj.currentType);
        obj.say();
    </script>
</head>
<body>
</body>
</html>

image-20210904150501393

posted @ 2021-09-04 15:06  BNTang  阅读(39)  评论(0编辑  收藏  举报