当前位置:网站首页>ES6高级-利用原型对象继承方法
ES6高级-利用原型对象继承方法
2022-07-26 02:24:00 【setTimeout()】
我们来看下面的代码:
<body>
<script>
function Father(uname, age) {
this.uname = uname;
this.age = age;
}
Father.prototype.money = function() {
console.log('money!');
}
function Son(uname, age) {
Father.call(this, uname, age);
}
Son.prototype = Father.prototype;
Son.prototype.exam = function() {
console.log('exam');
}
var son = new Son('son', 18);
console.log(son);
console.log(Father.prototype);
</script>
</body>输出结果:

我们就可以发现如果直接把父类的原型对象赋给子类的原型对象,虽然子类可以继承父类的方法,但是如果子类添加方法的话就会对父类造成影响。
原因是因为看下面这个图:

把子原型对象指向了父原型对象,所以修改子原型对象也会修改父原型对象,所以得换一个方法实现方法继承。
更改代码为:
<body>
<script>
function Father(uname, age) {
this.uname = uname;
this.age = age;
}
Father.prototype.money = function() {
console.log('money!');
}
function Son(uname, age) {
Father.call(this, uname, age);
}
Son.prototype = new Father();
Son.prototype.exam = function() {
console.log('exam');
}
var son = new Son('son', 18);
console.log(son);
console.log(Father.prototype);
</script>
</body>输出结果为:

这样就正常了,原理看下面这张图:

但是上面的代码也有问题,就是这句:Son.prototype = new Father();,这样写的话Son的prototype就没有constructor了,所以需要指回原来的原型对象,加上Son.prototype.constructor=Son();
边栏推荐
猜你喜欢
![[2021] [paper notes] 6G technology vision - otfs modulation technology](/img/50/577ad05bc16e80d1c68eec7b6da988.png)
[2021] [paper notes] 6G technology vision - otfs modulation technology

Postman reported JSON serialization error

Bitmap这个“内存刺客”你要小心~

Tenant issues.

I came to the library applet check-in process analysis

Turn on the LED

I.MX6UL核心模块使用连载-nand flash读写测试 (三)

prometheus+process-exporter+grafana 监控进程的资源使用

Sword finger offer 28. symmetric binary tree

Ggplot2 learning summary
随机推荐
1. Mx6ul core module use serial TF card read / write test (V)
18_请求文件
Exclusive interview with ringcentral he Bicang: empowering future mixed office with innovative MVP
I.MX6UL核心模块使用连载-eMMC读写测试 (四)
必会面试题:1.浅拷贝和深拷贝_深拷贝
What can EAM system help enterprises do?
How to choose cloud note tool? What can I do with cloud notes?
What is JSX?
[pyqt5 packaged as exe]
本地仓库导致的报错
prometheus+process-exporter+grafana 监控进程的资源使用
Prove that perfect numbers are even
1. Mx6ul core module uses serial EMMC read / write test (IV)
力扣148:排序链表
[C language brush leetcode] 443. Compressed string (m)
Design and driver transplantation of matrix keyboard circuit of Ti am335x industrial control module
2022-07-17
1. Mx6ul core module use serial RTC test (XII)
19_ Request forms and documents
ERROR: could not extract tar starting at offset 000000000000020980+9231072+2