JavaScript继承方式(4)

4,继承工具函数四

/**
 * @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]);
}

 

定义父类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;
	}
});

子类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

从输出看可以看到子类Man的确继承了父类的属性和方法。

你可能感兴趣的:(JavaScript)