每个函数上边都有一个原型 prototype
// 我们 去创建一个构造函数
function Person(){
this.name = ' 这是世祖'
this.age = '80'
this.cart = 'BMW'
}
// 有一天 Person 嗝屁了 留下来了一些遗产,需要他的儿子去继承他的车和钱
function PersonChildren(){
}
//继承
PersonChildren.prototype = new Person()
//查看 person 的遗产 是否继承
let personChildren = PersonChildren.prototype
console.log(personChildren);
//输出结果:
// Person {name: " 这是世祖", age: "80", cart: "BMW"}
// age: "80"
// cart: "BMW"
// name: " 这是世祖"
// __proto__:
// constructor: ƒ Person()
// arguments: null
// caller: null
// length: 0
// name: "Person"
// prototype: {constructor: ƒ}
// __proto__: ƒ ()
// [[FunctionLocation]]: index.html:29
// [[Scopes]]: Scopes[2]
// __proto__: Object
- 可以看到person的儿子已经继承了他爸爸的遗产
- 但是我们也可以看到 PersonChildren.prototype 的原型已经被覆盖掉了;
- 我们可以使用一下方法,让他的原型重新指向他自己,这样他就有了自己的原型
PersonChildren.prototype.constructor=PersonChildren
console.log(PersonChildren.prototype);
- 输出结果如下
Person {name: " 这是世祖", age: "80", cart: "BMW", constructor: ƒ}
age: "80"
cart: "BMW"
constructor: ƒ PersonChildren()
arguments: null
caller: null
length: 0
name: "PersonChildren"
prototype: Person
age: "80"
cart: "BMW"
constructor: ƒ PersonChildren()
name: " 这是世祖"
__proto__: Object
__proto__: ƒ ()
[[FunctionLocation]]: index.html:38
[[Scopes]]: Scopes[2]
name: " 这是世祖"
__proto__: Object
总结:以此类推越继承越多 ,这就是原型链的的继承!