Home > Article > Web Front-end > Detailed explanation of JavaScript inheritance method (4)
This article mainly explains the JavaScript inheritance method in detail, and mainly shares it with you in the form of code. I hope it can help you.
1, inherit the tool function
/** * @param {String} className * @param {String/Function} superClass * @param {Function} classImp */ function $class(className, superClass, classImp){ if (superClass === '') superClass = Object; function clazz() { if (typeof this.init == "function") { this.init.apply(this, arguments); } } var p = clazz.prototype = new superClass(); var _super = superClass.prototype; window[className] = clazz; classImp.apply(p, [_super]); }
Define the parent class Person
/** * 父类 Person */ $class('Person','',function(){ this.init = function(name){ this.name = name; }; this.getName = function(){ return this.name; }; this.setName = function(name){ this.name = name; } });
Subclass Man
/** * 子类 Man */ $class('Man', Person, function(supr){ this.init = function(name, age){ supr.init.apply(this,[name]); // 该句很重要 this.age = age; }; this.getAge = function(){ return this.age; }; this.setAge = function(age){ this.age = age; }; }); var m = new Man('Jack',25); console.log(m.name); // Jack console.log(m.age); // 25
You can see the subclass from the output Man does inherit the properties and methods of the parent class.
The above is the detailed content of Detailed explanation of JavaScript inheritance method (4). For more information, please follow other related articles on the PHP Chinese website!