对象中
__proto__
组成的链条我们称之为原型链
- 对象在查找属性和方法的时候,会先在当前对象查找
<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>
- 如果当前对象中找不到想要的,会依次去上一级原型对象中查找
<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>
- 如果找到
Object
原型对象都没有找到,就会报错
<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>