<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
</body>
<script>
//总论:prototype原型链继承法
// 定义父类 F
function F() {
this.abc = "slkfslfjssdfsdf";
}
// 在父类 F 的原型上定义方法和属性
F.prototype.getAbc = function () {
console.log(this.abc, "abc");
};
F.prototype.cbd = "2342342424";
// 定义子类 child
function child() {
// 调用父类构造函数,继承父类的私有属性
F.call(this);
this.mmd = "slkfjslfjslkfdsdf";
}
// 设置子类的原型对象为父类的原型对象的一个副本
child.prototype = Object.create(F.prototype);
// 确保子类的构造函数指向子类本身
child.prototype.constructor = child;
// 在子类的原型上添加新属性
child.prototype.childPrototype1 = "sdlfkjsldfkjsdf";
child.prototype.cbd = "child-cbd";
// 测试代码
console.dir(child, "child");
var demo = new child();
console.log(demo, "demo");
demo.getAbc();
console.log(demo.cbd, "demo.cbd,child.cbd"); // 打印结果: child-cbd
/*
总结:
1、最好的继承方式应该是prototype对象的原型链去继承父类的prototype对象
2、父类私有属性继承,可以通过子类函数中父类call this 方式继承,相当于子类执行一遍父类的this私有属性声明
3、通过prototype原型链继承的方式,可以共用父类的原型内存,且不妨碍子类prototype声明自身的原型属性而不影响父类的原型对象的内存
*/
</script>
</html>
前端工程师、程序员