当前位置:网站首页>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();
边栏推荐
- Nacos Development Manual
- 1. Color inversion, logarithmic transformation, gamma transformation source code - miniopencv from zero
- Introduction to backup and recovery Cr
- Zhong Xuegao, who cannot be melted, cannot escape the life cycle of online celebrity products
- 根据csv文件某一列字符串中某个数字排序
- Wincc7.5 download and installation tutorial (win10 system)
- 【MySQL】鎖
- Is it safe to open an account in Zheshang futures?
- [brush questions] top101 must be brushed in the interview of niuke.com
- JVM performance tuning and practical basic theory - Part 1
猜你喜欢
2. File operation - write
JVM performance tuning and practical basic theory - Part 1
Chinese Remainder Theorem (Sun Tzu theorem) principle and template code
【MySQL】鎖
matplotlib. Widgets are easy to use
IoT -- 解读物联网四层架构
2022.02.13 - NC003. Design LRU cache structure
Step by step guide to setting NFT as an ens profile Avatar
C language custom type: struct
IP lab, the first weekly recheck
随机推荐
Sort according to a number in a string in a column of CSV file
使用 BR 恢复 S3 兼容存储上的备份数据
The resources of underground pipe holes are tight, and the air blowing micro cable is not fragrant?
Pyqt5 development tips - obtain Manhattan distance between coordinates
1202 character lookup
How to use information mechanism to realize process mutual exclusion, process synchronization and precursor relationship
使用 Dumpling 备份 TiDB 集群数据到兼容 S3 的存储
VMware virtualization cluster
China polyether amine Market Forecast and investment strategy report (2022 Edition)
Convolution, pooling, activation function, initialization, normalization, regularization, learning rate - Summary of deep learning foundation
IP lab, the first weekly recheck
【MySQL】鎖
MySQL learning record 11jdbcstatement object, SQL injection problem and Preparedstatement object
ESP series pin description diagram summary
String to leading 0
leetcode刷题 (5.29) 哈希表
Migrate data from CSV files to tidb
From monomer structure to microservice architecture, introduction to microservices
JVM performance tuning and practical basic theory - Part 1
On the day of resignation, jd.com deleted the database and ran away, and the programmer was sentenced