原理: 将父类的实例,赋值给子类的原型和原型上一个属性superClass,将子类的实例赋值给孙类的原型和原型上一个属性superClass。 孙类实例继承了孙类,子类和父类原型上所有的属性和方法,并可以通过superClass向上访问原型链,同理,子类实例继承了子类和父类原型上的属性和方法,并可以通过superClass访问子类原型,是不是有点绕,没关系,下面给出了具体代码:
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Document</title>
</head>
<body>
<img src="src/img/pic.png"/>
<script type="text/javascript">
function Person() {}
Person.prototype = {
name: 'iwen',
run: function () {
console.log('run')
}
}
function Man() {}
Man.prototype = new Person()
Man.prototype.superClass = new Person()
Man.prototype.name = 'iwen2'
Man.prototype.run = function () {
console.log('run2')
}
function Son() {}
Son.prototype = new Man()
Son.prototype.superClass = new Man()
Son.prototype.name = 'iwen3'
Son.prototype.run = function () {
console.log('run3')
}
var child = new Son()
console.log(child.superClass)
console.log(child.superClass.superClass)
</script>
</body>
</html>
打印结果