当前位置:网站首页>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();
边栏推荐
- hcip--mpls
- Synchronized solves problems caused by sharing
- China vanadium battery Market Research and future prospects report (2022 Edition)
- 从表中名称映射关系修改视频名称
- pcd转ply后在meshlab无法打开,提示 Error details: Unespected eof
- sys. argv
- Rviz仿真时遇到机器人瞬间回到世界坐标原点的问题及可能原因
- Huawei cloud OBS file upload and download tool class
- Wincc7.5 download and installation tutorial (win10 system)
- MySQL learning record 10getting started with JDBC
猜你喜欢
[MySQL] log
[research materials] 2021 live broadcast annual data report of e-commerce - Download attached
Chinese Remainder Theorem (Sun Tzu theorem) principle and template code
【MySQL】日志
根据csv文件某一列字符串中某个数字排序
2022 Inner Mongolia latest water conservancy and hydropower construction safety officer simulation examination questions and answers
Zhong Xuegao, who cannot be melted, cannot escape the life cycle of online celebrity products
Pointer advanced --- pointer array, array pointer
2022.02.13 - NC002. sort
Online yaml to CSV tool
随机推荐
Chinese Remainder Theorem (Sun Tzu theorem) principle and template code
JVM 快速入门
IP lab, the first weekly recheck
hcip--mpls
LDAP应用篇(4)Jenkins接入
[cloud native topic -45]:kubesphere cloud Governance - Introduction and overall architecture of enterprise container platform based on kubernetes
[2022 Guangdong saim] Lagrange interpolation (multivariate function extreme value divide and conquer NTT)
【MySQL】锁
Sort according to a number in a string in a column of CSV file
Rviz仿真时遇到机器人瞬间回到世界坐标原点的问题及可能原因
Image fusion -- challenges, opportunities and Countermeasures
IoT -- 解读物联网四层架构
Analysis of pointer and array written test questions
Introduction to number theory (greatest common divisor, prime sieve, inverse element)
面向个性化需求的在线云数据库混合调优系统 | SIGMOD 2022入选论文解读
Summary of MySQL index failure scenarios
[research materials] 2021 live broadcast annual data report of e-commerce - Download attached
Pyqt5 development tips - obtain Manhattan distance between coordinates
China polyether amine Market Forecast and investment strategy report (2022 Edition)
Yyds dry goods inventory three JS source code interpretation eventdispatcher