Home > Web Front-end > JS Tutorial > Detailed explanation of JavaScript inheritance method (4)

Detailed explanation of JavaScript inheritance method (4)

零到壹度
Release: 2018-03-22 14:33:23
Original
1439 people have browsed it

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]);
}
Copy after login

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;
}
});
Copy after login

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
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template