JavaScript-属性注意点

首先我给出了如下一段代码,obj 对象的构造函数当中并没有 currentType 这个属性那么就会去原型对象当中进行查找,如下也给出了输出结果

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>JavaScript-属性注意点</title>
    <script>
        function Person(myName, myAge) {
            this.name = myName;
            this.age = myAge;
        }

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

image-20210904204555178

在给一个对象不存在的属性设置值的时候,不会去原型对象中查找,如果当前对象没有就会给当前对象新增一个不存在的属性,这个就本章节所需要讲解的注意点代码与输出结果如下所示

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>JavaScript-属性注意点</title>
    <script>
        function Person(myName, myAge) {
            this.name = myName;
            this.age = myAge;
        }

        Person.prototype = {
            constructor: Person,
            currentType: "人",
            say: function () {
                console.log("hello world");
            }
        }
        let obj = new Person("BNTang", 34);

        obj.currentType = "新设置的值";
        console.log(obj.currentType);
        console.log(obj.__proto__.currentType);
    </script>
</head>
<body>
</body>
</html>

image-20210904204657380

posted @ 2021-09-04 20:48  BNTang  阅读(37)  评论(0编辑  收藏  举报