会js与jq的后端开发如何愉快的转前端:第二篇-第三节:es6-面向对象完毕-继承
第二篇 - 第二节:es6 - 面向对象 - 继承#
ES6 之前并没有给我们提供 extends 继承。我们可以通过构造函数 + 原型对象模拟实现继承,被称为组合继承。
call 方法,继承前必须知道如何用#
- call () 可以调用函数
fn.call();
- call () 可以改变这个函数的 this 指向 此时这个函数的 this 就指向了 o 这个对象
代码
<body>
<script>
// call 方法
function fn(x, y) {
console.log('我想喝手磨咖啡');
console.log(this);
console.log(x + y);
}
var o = {
name: 'andy'
};
fn.call(o, 1, 2);
</script>
</body>
运行结果
借用父构造函数继承属性#
- 父构造函数
function Father(uname, age) {
// this 指向父构造函数的对象实例
this.uname = uname;
this.age = age;
}
2 . 子构造函数
function Son(uname, age, score) {
// this 指向子构造函数的对象实例
Father.call(this, uname, age);
this.score = score;
}
这里 this 指向 son 我把 father 的属性指向 son。
那么 son 就可以使用 father 的 uname 和 age 属性了
this 自己 uname age 传给父类的参数
全文代码:
<body>
<script>
// 借用父构造函数继承属性
// 1. 父构造函数
function Father(uname, age) {
// this 指向父构造函数的对象实例
this.uname = uname;
this.age = age;
}
// 2 .子构造函数
function Son(uname, age, score) {
// this 指向子构造函数的对象实例
// 这里this 指向son 我把father的属性指向 son。
// 那么son就可以使用father 的 uname 和 age属性了
// this 自己 uname age 传给父类的参数
Father.call(this, uname, age);
this.score = score;
}
var son = new Son('大幂幂', 18, 100);
console.log(son);
</script>
</body>
运行结果
借用原型对象继承方法#
依然是上面的代码。
我们新写 一个原型对象的公共方法 money
Father.prototype.money = function() {
console.log(100000);
};
那么问题来了,进行 console.log() 调用。
结果如下:
发现 我们这个函数中,没有 money ()
这是因为,你的 money 并不是在 father 函数内部。所以没有给继承过来。
那么如何继承呢?#
- 直接赋值。 可以这么做,但是这样直接赋值会有问题,如果修改了子原型对象,父原型对象也会跟着一起变化
- 借用原型对象。整一个公共的然后再用,从而实现继承的效果。
借用原型对象实现代码
<body>
<script>
// 借用父构造函数继承属性
// 1. 父构造函数
function Father(uname, age) {
// this 指向父构造函数的对象实例
this.uname = uname;
this.age = age;
}
Father.prototype.money = function() {
console.log(100000);
};
// 2 .子构造函数
function Son(uname, age, score) {
// this 指向子构造函数的对象实例
Father.call(this, uname, age);
this.score = score;
}
// Son.prototype = Father.prototype; 这样直接赋值会有问题,如果修改了子原型对象,父原型对象也会跟着一起变化
Son.prototype = new Father();
// 如果利用对象的形式修改了原型对象,别忘了利用constructor 指回原来的构造函数
Son.prototype.constructor = Son;
// 这个是子构造函数专门的方法
Son.prototype.exam = function() {
console.log('孩子要考试');
}
var son = new Son('大幂幂', 18, 100);
console.log(son);
console.log(Father.prototype);
console.log(Son.prototype.constructor);
</script>
</body>
截图:
本作品采用《CC 协议》,转载必须注明作者和本文链接
推荐文章: