SoFunction
Updated on 2025-04-06

New attempts to inherit JavaScript class

What I've tried today is how to use inheritance mechanisms, multi-layer inheritance and more aspects of calling the parent class's constructs more like other languages.
What I hope to achieve:
Copy the codeThe code is as follows:

function A(){
alert('a');
}
function B(){
this.$supClass();
alert('b');
}
extend(B,A);
function C(){
this.$supClass();
alert('c');
}
extend(C,B);
var c = new C();
alert( c instanceof A ); //true
alert( c instanceof B ); //true
alert( c instanceof C ); //true

Example:

[Ctrl+A Select all Note:Introducing external Js requires refreshing the page before execution]

My extend is written like this:
Copy the codeThe code is as follows:
 
function extend(subClass,supClass){ 
var fun = function(){}, 
prototype = ; 
= ; 
= new fun(); 
for(var i in prototype){ 
[i] = prototype[i]; 

subClass.$supClass = supClass; 
.$supClass = function(){ 
var supClass = .$supClass; 
if(typeof supClass == 'function'){ 
(this,arguments); 
this.$supClass = supClass; 

}; 
= subClass; 
return subClass; 
}

Maybe you will ask, why not write this way:
Copy the codeThe code is as follows:

function extend(subClass,supClass){
var fun = function(){},
prototype = ;
= ;
= new fun();
for(var i in prototype){
[i] = prototype[i];
}
.$supClass = function(){
(this,arguments);
};
= subClass;
return subClass;
}

This seems to be fine, and only first-level inheritance will run well, but if multiple-level inheritance is incurred, it will cause a dead loop because:
Copy the codeThe code is as follows:

.$supClass = function(){
(this,arguments);
};

This method will be overwritten and rewritten, causing a dead loop.
My approach is to use the $supClass attribute of the class to point to the parent class it inherits. There is also a $supClass method in the prototype. This $supClass must be executed in the class constructor for the first time. When executing prototype.$supClass, the $supClass of the class will be obtained through .$supClass, and then executed in this by applying. In this way, $subClass can obtain the class's parent class constructor and execute it according to different sources.