继承:是面向对象的三大特征之一,详情看这个面向对象与面向过程 - 掘金 (juejin.cn)
还有这个:构造函数,原型对象,实例对象 - 掘金 (juejin.cn)
继承: 一个对象(子) 拥有 另一个对象(父) 所有的成员
原型继承 : 把 父对象 作为子对象构造函数的 原型。
也就是把一个对象father,添加到另一个对象son的构造函数Son的prototype中,这样 son 就能使用 father 里面的属性和方法了
//父对象实例
let father = {
house:{
address : '汤臣一品',
price : 100000000
},
car : {
brand : '劳斯莱斯幻影',
price:15000000
}
}
//子对象构造函数
function Son(name,age){
this.name = name
this.age = age
}
/* 原型继承: 把父对象 作为 子对象构造函数的原型 */
Son.prototype = father
//子对象
let s1 = new Son('班长',20)
let s2 = new Son('ikun',30)
console.log(s1,s2)
console.log( s1.house )
console.log( s2.car )
原型链
原型链:每一个实例对象都有自己的原型,而原型也是对象,也有自己的原型,对象先访问自己的成员,自己没有就找原型,原型也没有就找原型的原型,以此类推,形成链式结构,就是原型链。原型链的终点为 null,如果还找不到,属性就为undefined,方法就报错 *** is not a function。
原型链的作用就是继承
//查看内置对象原型链
let arr = [10,20,30]
console.log(arr)
//(1)查看arr的原型
console.log( arr.__proto__.constructor )//Array
console.log( arr.__proto__ === Array.prototype )//true
//(2)查看arr的原型的原型
console.log( arr.__proto__.__proto__.constructor )//Object
console.log( arr.__proto__.__proto__ === Object.prototype )//true
//字符串原型链
let str = new String('abc')
console.log( str )
//查看str的原型
console.log( str.__proto__.constructor ) //String
console.log( str.__proto__ === String.prototype )//true
//查看str的原型的原型
console.log( str.__proto__.__proto__.constructor )//Object
console.log( str.__proto__.__proto__ === Object.prototype )//true