01-ES5原型链的继承
<script>
// ES6继承
class Person { }
class Student extends Person { }
console.log(new Student())
// ES5的原型继承
function Animal() { }
Animal.prototype.say = function () {
console.log('喔')
}
function Dog() { }
// console.log(new Dog())
// let d1 = new Dog()
// d1.say()
// Dog的__proto__自动指向Object.prorotype
// 实现:Dog.prototype.__proto__ = Animal.prototype
Dog.prototype.__proto__ = Animal.prototype
let d2 = new Dog()
console.log(d2)
d2.say()
// 如果要用ES5实现继承:具体步骤如下
// 1. 先定义构造函数
// 2. 挂载原型方法
// 3. 实现构造函数的原型继承
// 4. 最后才实例化对象:调用原型方法
</script>
注意:
// 如果要用ES5实现继承:具体步骤如下
// 1. 先定义构造函数
// 2. 挂载原型方法
// 3. 实现构造函数的原型继承
// 4. 最后才实例化对象:调用原型方法
02-ES5原型链的继承-创建元素继承案例
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.current {
/* 浮动 */
float: left;
/* 宽高 */
width: 200px;
height: 200px;
border-radius: 50%;
border: 20px solid skyblue;
/* 内容居中 */
text-align: center;
line-height: 200px;
/* 字体 */
font-size: 24px;
}
</style>
</head>
<body>
<script>
// 实现创建元素的继承
// 1. 增加一个构造函数:能够创建元素
function CreateElement(tag, className, text) {
this.ele = document.createElement(tag)
this.ele.classList.add(className)
this.ele.innerText = text
}
// 2. 增加原型方法:实现appendTo
CreateElement.prototype.appendTo = function (selector) {
document.querySelector(selector).appendChild(this.ele)
}
// 测试
const div = new CreateElement('div', 'current', '做人开心就好')
div.appendTo('body')
// 3. 创建一个构造函数:创建图片元素
function CreateImg(src, className) {
// this.ele = document.createElement('img')
// this.ele.classList.add(className)
// 3.1 借调父构造函数:在原来实现创建元素的基础上,增加一个src属性即可
CreateElement.call(this, 'img', className, '')
this.ele.src = src
}
// 4. 实现继承效果
CreateImg.prototype.__proto__ = CreateElement.prototype
const img = new CreateImg('images/b1.jpg', 'current')
img.appendTo('body')
// 原型的继承中:必用借调
</script>
</body>
</html>
注意:
1.原型的继承中:必用借调