当前位置:网站首页>原型继承
原型继承
2022-07-21 18:06:00 【梁什么鸭,】
让P2继承P1,下面直接将P1的属性赋给P2,这种方法不建议使用
<script>
function P1() {
this.name = arguments[0];
this.age = arguments[1];
}
P1.prototype.sayName = function () {
alert(this.name);
};
// 通过复制,来继承P1
function P2() {
this.name = arguments[0];
this.age = arguments[1];
}
</script>
function P2() {
// obj2 = this
this.name = arguments[0];
this.age = arguments[1];
}
// 在实例P2时,执行了。
// 那么这些属性也就挂载到了实例的对象中
new P2();
那么我们只需要将P1中的属性挂载到实例的对象中就可
function P1(opt) {
this.name = opt.name;
this.age = opt.age;
}
P1.prototype.sayName = function () {
alert(this.name);
};
function P2(opt) {
// 继承基类所有
P1.call(this, opt)
// 自行扩展
this.sex = opt.sex;
}
// 方案一: 因为原型是对象,引用类型数据。如果直接将P1的原型赋给P2,那么当扩展P2的原型是,同时也会修改P1
/*P2.prototype = P1.prototype;*/
// 方案二: 使P1实例的对象obj1挂载到 P2的原型上
P2.prototype = new P1({});
// 此时再在P2的原型上扩展,就不会影响P1的原型
P2.prototype.add = function () {
alert(this.name)
}
const o1 = new P1({
name: 'Lee',
age: 18
});
const o2 = new P2({
name: '梁什么鸭',
age: 18,
sex: 'girl'
});
o1.sayName();
o2.add();
当输出o2
这是因为当 P2.prototype = new P1({});,把P1的私有属性扩展到P2的原型上去了
但逻辑上不影响,因为要的私有属性已经继承过来了
要去掉这些值为undefined 的属性,可用方案三,借助一个无用的函数
// 方案三:
function c() {} // c类没有私有属性,是空的
c.prototype = P1.prototype
P2.prototype = new c();
输出 o2
还有个跟前面三个方案没有关系的方案4
方案一淘汰的主要原因是因为它们指向的内存地址相同,修改一个,另一个的原型也同时修改
// 方案四:与前面三个方案无瓜葛
for(var key in P1.prototype) {
P2.prototype[key] = P1.prototype[key];
}
方案四不能遍历P1原型的原型
推荐用方案三,都可遍历到
边栏推荐
猜你喜欢
High frequency leetcode deep search part: Sword finger offer 36 Binary search tree and bidirectional linked list
响应式布局——移动web像素
Performance optimization
office2016—word不能使用输入法,只能输入英文问题
cookie
andorid 查看 Activity任务栈
flex布局的常用属性
27.最长递增子序列
EAS Web BIM Start Access prompt 500 Error
排序方法--冒泡排序(使用数组实现一串数字的从大到小或从小到大排序)
随机推荐
EAS Web BIM Start Access prompt 500 Error
SqlServer将数据库中的表复制到另一个数据库
How much do you know about the benefits of encouraging enterprise knowledge sharing?
微信小程序Text限定行数
simplest-i18n
Three ways to turn the extra part of the text into an ellipsis
Handler学习
如何快速的学习嵌入式
生物化学复习VI·生物氧化
30.重排链表
Thunderbolt interview questions
The error interface of EAS web page preview is blank
2022年 iuap 春季培训数据中台培训报道
andorid 查看 Activity任务栈
响应式布局——视口viewport和常用单位
MVP_用户登录实例2_测试用例
让盒子居中且距离浏览器左右各100px做动画
Responsive layout viewport and common units
23.螺旋矩阵
Oracle error list