首先让我们看下使用Crockford式继承的调用方式:
注意:代码中的method、inherits、uber都是自定义的对象,我们会在后面的代码分析中详解。
// 定义Person类 function Person(name) { this.name = name; } // 定义Person的原型方法 Person.method("getName", function() { return this.name; }); // 定义Employee类 function Employee(name, employeeID) { this.name = name; this.employeeID = employeeID; } // 指定Employee类从Person类继承 Employee.inherits(Person); // 定义Employee的原型方法 Employee.method("getEmployeeID", function() { return this.employeeID; }); Employee.method("getName", function() { // 注意,可以在子类中调用父类的原型方法 return "Employee name: " + this.uber("getName"); }); // 实例化子类 var zhang = new Employee("ZhangSan", "1234"); console.log(zhang.getName()); // "Employee name: ZhangSan"
这里面有几处不得不提的硬伤: 子类从父类继承的代码必须在子类和父类都定义好之后进行,并且必须在子类原型方法定义之前进行。 虽然子类方法体中可以调用父类的方法,但是子类的构造函数无法调用父类的构造函数。 代码的书写不够优雅,比如原型方法的定义以及调用父类的方法(不直观)。
当然Crockford的实现还支持子类中的方法调用带参数的父类方法,如下例子:
function Person(name) { this.name = name; } Person.method("getName", function(prefix) { return prefix + this.name; }); function Employee(name, employeeID) { this.name = name; this.employeeID = employeeID; } Employee.inherits(Person); Employee.method("getName", function() { // 注意,uber的第一个参数是要调用父类的函数名称,后面的参数都是此函数的参数 // 个人觉得这样方式不如这样调用来的直观:this.uber("Employee name: ") return this.uber("getName", "Employee name: "); }); var zhang = new Employee("ZhangSan", "1234"); console.log(zhang.getName()); // "Employee name: ZhangSan"
首先method函数的定义就很简单了:
Function.prototype.method = function(name, func) { // this指向当前函数,也即是typeof(this) === "function" this.prototype[name] = func; return this; };
新闻热点
疑难解答
图片精选