当前位置:网站首页>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();
边栏推荐
- Char to leading 0
- Yyds dry goods inventory three JS source code interpretation eventdispatcher
- LDAP应用篇(4)Jenkins接入
- Research Report on supply and demand and development prospects of China's high purity aluminum market (2022 Edition)
- sys. argv
- JVM performance tuning and practical basic theory - Part 1
- Leetcode question brushing (5.28) hash table
- MySQL learning record 07 index (simple understanding)
- Fibonacci sequence
- Zhong Xuegao, who cannot be melted, cannot escape the life cycle of online celebrity products
猜你喜欢
2022.02.13 - NC002. sort
[research materials] 2022 enterprise wechat Ecosystem Research Report - Download attached
ESP系列引脚說明圖匯總
Yyds dry goods inventory three JS source code interpretation eventdispatcher
2022.02.13 - NC001. Reverse linked list
How to use information mechanism to realize process mutual exclusion, process synchronization and precursor relationship
NFT smart contract release, blind box, public offering technology practice -- jigsaw puzzle
根据csv文件某一列字符串中某个数字排序
tree树的精准查询
堆排序详解
随机推荐
图像融合--挑战、机遇与对策
China vanadium battery Market Research and future prospects report (2022 Edition)
IOT -- interpreting the four tier architecture of the Internet of things
ESP series pin description diagram summary
Colorlog combined with logging to print colored logs
704 二分查找
hcip--mpls
Configuring OSPF load sharing for Huawei devices
The ECU of 21 Audi q5l 45tfsi brushes is upgraded to master special adjustment, and the horsepower is safely and stably increased to 305 horsepower
How to use information mechanism to realize process mutual exclusion, process synchronization and precursor relationship
Char to leading 0
Migrate data from a tidb cluster to another tidb cluster
2022.02.13 - NC004. Print number of loops
2022.02.13 - NC003. Design LRU cache structure
Make learning pointer easier (3)
[research materials] 2021 live broadcast annual data report of e-commerce - Download attached
JS select all and tab bar switching, simple comments
China polyether amine Market Forecast and investment strategy report (2022 Edition)
Beijing invitation media
2022.02.13 - NC002. sort