首先我给出了如下一段代码,obj 对象的构造函数当中并没有 currentType 这个属性那么就会去原型对象当中进行查找,如下也给出了输出结果
<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>
在给一个对象不存在的属性设置值的时候,不会去原型对象中查找,如果当前对象没有就会给当前对象新增一个不存在的属性,这个就本章节所需要讲解的注意点代码与输出结果如下所示
<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>