首页 > 文章列表 > js原型链继承的关系

js原型链继承的关系

js 原型链
434 2022-08-06

1、构造函数有原型对象,原型对象有指针指向结构函数,每个实例都有内部指针指向原型对象。

2、Father通过new给Children的原型对象赋值一个实例,从而实现Children继承Father。

实例

// 父构造函数
function Father() {
    this.name = "father"
    this.house = "cottage"
}
// 原型方法
Father.prototype.alertName = function () {
    console.log(this.name)
}
// 创造实例
let f = new Father()
 
f.alertName()//father
 
// 子构造函数
function Children() {
    this.name = "children"
}
// 实现继承:子构造函数的原型对象=父构造函数的实例对象
Children.prototype = new Father()
// 创建子实例
let c = new Children()
// 儿子就继承了父亲的所有属性(大别墅),并且获得了自己的名字
 
c.alertName()//children
 
console.log(c.house)//cottage

推荐操作环境:windows7系统、jquery3.2.1版本,DELL G3电脑。