北流科技网站建设,宜兴网站制作,自己建设一个平台网站多少钱,广告设计案例网站借用原型对象继承父类型方法
目的: 儿子继承父类属性和方法#xff0c;父类之后新增的方法不会被儿子继承。
前言#xff1a;
先理解一个问题#xff1a;
Son.prototype Father.prototype; 这一操作相当于把Son的原型对象指向Father。
意味着Son的prototype的地址与Fa…借用原型对象继承父类型方法
目的: 儿子继承父类属性和方法父类之后新增的方法不会被儿子继承。
前言
先理解一个问题
Son.prototype Father.prototype; 这一操作相当于把Son的原型对象指向Father。
意味着Son的prototype的地址与Father一致如果我给Son新增函数那么Father也会同步新增。 具体代码
function Father(uname, age) {this.uname uname;this.age age;
}
Father.prototype.money function() {console.log(100000);};
function Son(uname, age, score) {Father.call(this, uname, age);this.score score;
}
Son.prototype Father.prototype;let son new Son(刘德华, 18, 100);
console.log(Son.prototype);
console.log(Father.prototype);结果 分析
我们的初衷是儿子继承父类属性和方法父类之后新增的方法不会被儿子继承。
很明显儿子和父亲的成员函数和属性都一致这是由于儿子和父类地址一致导致的。 解决方案
Son.prototype new Father();
首先用new创建一个父类的实例对象然后让Son的原型对象指向这个新创建的对象即可。 从下往上理解
Son原型对象指向Father实例对象继承Father实例对象的属性和方法
Father实例对象含有__proto__属性可以使用Father原型对象的新增的方法
Father原型对象可以新增函数
此时如果Son新增函数由于Son和Father实例对象地址一致只会影响到Father实例对象而不会影响到Father原型对象上。 总结
将子类所共享的方法提取出来让子类的 prototype 原型对象 new 父类()
通过父类实例化对象开辟额外空间就不会影响原来父类的原型对象。
有一说一采用了深拷贝的思想。 Code: // 借用父构造函数继承属性
// 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);参考
可以看这两集
https://www.bilibili.com/video/BV1DY41177dM?p37spm_id_frompageDrivervd_source30a98e03cd5a7bbfaeb4416fc48542e2