当前位置:网站首页>JS inheritance method
JS inheritance method
2022-07-06 08:28:00 【Wind billows】
new A few things to do :
1. Create an empty object in the constructor
2. Functional this Point to empty object , And the implicit prototype of this object (proto) Point to the prototype of the constructor (prototype)
3. Execute the code line by line
4. Implicitly return this object
new In fact, the constructor prototype (prototype) The attribute on is placed on the prototype chain (proto) On , Then when the instantiated object takes values, it will take values from the prototype chain , On the instantiated object prototype It's gone
Inherit : Objects created by constructors , You can directly inherit the properties and methods on the constructor prototype .
Implement inheritance between constructors :A There are properties and methods in constructors ,B Constructors can also be used (B Inherited from A、A yes B Parent class of )
1. Traditional inheritance ( Class inheritance )( Prototype chain inheritance )
function A(){
}
A.prototype.name = "123";// stay A Add properties to the prototype
function B(){
}
B.prototype.age = '18';// stay B Add properties to the prototype
// send B The prototype of points to A The prototype of the
// Give Way B Creating objects can use A Properties and methods on the stereotype
// The following three methods are the same
B.prototype = A.prototype;
//B.prototype = new A() // Class inheritance
// var b = new B();b.__proto__ = A.prototype;
var obj = new B();
console.log(obj.name); // 123
console.log(obj.age); // undefined
// Throw away the inherited properties and methods of itself
principle : send B The prototype of points to A The prototype of the ;
advantage : A simple line of code ,B The created object inherits A All properties and methods on the prototype
shortcoming :
■ A child class can only inherit one parent class ( Because the inheritance method directly modifies subclasses prototype, If you modify it again , Will cover it )
■ B The methods and properties on the prototype are discarded ,B The created object cannot inherit itself
■ Subclass through prototype Inherited parent class , Only the parent class can pass attributes to the child class in one direction , Cannot pass parameter to parent class . Why pass parameters to the parent class ? If an attribute in the parent class has a dependency on parameters , At this point, the subclass inherits the parent class in new SuperClass() Shi Chuanshen
2. Inheritance by borrowing the constructor ( Constructor inheritance )
function A1(name) {
this.name = "111"
}
function A2(arr) {
this.arr = [1, 2, 3]
}
function A3(f) {
this.f = f
}
function A4() {
this.qq = 1529588254;
}
function B(name, arr, f) {
A1.call(this, name);
A2.call(this, arr);
A3.call(this, f);
A4.call(this)
}
var b = new B(111, [2, 6, 9], function() {
console.log(666);
})
console.log(b);
b The results are as follows
principle : Call methods in other constructors , Construct your own data
advantage : You can inherit properties from multiple parent classes , You can dynamically pass the required parameters to build data
shortcoming : Cannot inherit properties and methods from the prototype , Cannot inherit new attributes added outside the constructor
3. Combination inheritance
// Borrow constructor
function User(name, age, phone, ID) {
this.name = name;
this.age = age;
this.phone = phone;
this.id = ID;
}
User.sayHello = function() {
console.log(` My name is ${
this.name}, My ID card ${
this.id}`);
}
// var user = new User(' Yan Zhen ',38,1111,2222);
// Realization VIP And User The inheritance relationship between Key steps 1
// send VIP The prototype of the Point to an empty object , The implicit prototype of an empty object is User The prototype of the
// That is to let VIP The implicit prototype of the prototype points to User The prototype of the
// Original pattern inheritance
VIP.prototype = Object.create(User.prototype);
function VIP(name, age, phone, ID, money) {
// Borrow the constructor of ordinary users to add attributes to their own objects
User.apply(this, arguments); Key steps 2
// User(name,age,phone,ID); // this =》 window
// User.call(this,name,age,phone,ID);// this -> {}
this.money = money;
}
VIP.prototype.update = function() {
this.money -= 1000;
console.log(' And spent it again. 1000 ocean ');
}
var vipUser = new VIP(' Yan Zhen ', 38, 1111, 2222, 50000000);
// VIP Inherit User
vipUser.sayHello(); // vipUser.__proto__ => Vip.prototype => Object.prototype
principle : Call methods in other constructors , While constructing individual data , Link yourself to the target through a transit object ( Parent ) On the prototype chain of function . You can call properties and methods on the parent prototype chain .
advantage : Be able to use properties and methods on the prototype chain of parent constructors , You can also build your own attributes through the parent
shortcoming :
4. The holy grail mode ( Combine parasitic inheritance )
// Inherit the prototype of one constructor from the prototype of another constructor
// The holy grail mode
// Encapsulate inheritance Encapsulate as a function
A.prototype.sayHello = function(){
console.log(this);
}
function A() {
}
function B() {
}
// Original pattern inheritance
// function inherit(son,father){
// // Implementation inheritance
// function F(){};
// F.prototype = father.prototype;
// son.prototype = new F();
// // take son The original constructor is restored to him
// son.prototype.constructor = son;
// // Record son Who inherited it originally
// son.prototype.uber = father.prototype;
// }
// inherit(B,A);
// console.log(B.prototype.constructor); // A
// var b = new B();
// b.sayHello();
// Put in after packaging Function Prototype chain of , Convenient to call
Function.prototype.inherit = function(Father){
// this -》 Called object
function F(){
}
F.prototype = Father.prototype;
this.prototype = new F();
// Make some notes , Record what the original attribute should be
this.prototype.constructor = this;
this.prototype.uber = Father.prototype;
}
B.inherit(A);
var b = new B();
b.sayHello();
边栏推荐
- sys. argv
- 2022 Inner Mongolia latest construction tower crane (construction special operation) simulation examination question bank and answers
- Pyqt5 development tips - obtain Manhattan distance between coordinates
- 2022 Inner Mongolia latest water conservancy and hydropower construction safety officer simulation examination questions and answers
- 面向个性化需求的在线云数据库混合调优系统 | SIGMOD 2022入选论文解读
- ESP系列引脚说明图汇总
- 2022.02.13 - 238. Maximum number of "balloons"
- Use dumping to back up tidb cluster data to S3 compatible storage
- Grayscale upgrade tidb operator
- Restore backup data on S3 compatible storage with tidb lightning
猜你喜欢
NFT smart contract release, blind box, public offering technology practice -- contract
Use Alibaba icon in uniapp
2022.02.13 - NC002. sort
Easy to use tcp-udp_ Debug tool download and use
[MySQL] lock
C语言 - 位段
Pyqt5 development tips - obtain Manhattan distance between coordinates
Cisp-pte practice explanation
tree树的精准查询
Sort according to a number in a string in a column of CSV file
随机推荐
Upgrade tidb with tiup
1204 character deletion operation (2)
[research materials] 2022 China yuancosmos white paper - Download attached
使用 TiDB Lightning 恢复 S3 兼容存储上的备份数据
Cisp-pte practice explanation
Research Report on supply and demand and development prospects of China's high purity aluminum market (2022 Edition)
CAD ARX gets the current viewport settings
Colorlog结合logging打印有颜色的日志
Vocabulary notes for postgraduate entrance examination (3)
根据csv文件某一列字符串中某个数字排序
Research Report on Market Research and investment strategy of microcrystalline graphite materials in China (2022 Edition)
China polyether amine Market Forecast and investment strategy report (2022 Edition)
[brush questions] top101 must be brushed in the interview of niuke.com
Upgrade tidb operator
Asia Pacific Financial Media | female pattern ladyvision: forced the hotel to upgrade security. The drunk woman died in the guest room, and the hotel was sentenced not to pay compensation | APEC secur
图像融合--挑战、机遇与对策
[luatos-air551g] 6.2 repair: restart caused by line drawing
Analysis of Top1 accuracy and top5 accuracy examples
Permutation and combination function
LDAP application (4) Jenkins access