通过Javascript:The Good Parts中的第5.4章的示例代码,以下内容用于演示使用函数模式调用超级方法:
Object.method('superior', function (name) {
var that = this, method = that[name];
return function () {
return method.apply(that, arguments);
};
});
这将使用如下(其中“cat”是另一个定义了'get_name'函数的构造函数):
var coolcat = function (spec) {
var that = cat(spec),
super_get_name = that.superior('get_name');
that.get_name = function (n) {
return 'like ' + super_get_name( ) + ' baby';
};
return that;
};
但是,在运行示例代码时,F12工具显示以下内容:
未捕获TypeError:对象函数Object(){[native code]}没有方法'method'。
我在这里缺少什么?
答案 0 :(得分:4)
道格拉斯·克罗克福德使用以下内容(在本书第4页中定义)
Function.prototype.method = function (name, func) {
this.prototype[name] = func;
return this;
};
答案 1 :(得分:1)
这是因为您的代码中未定义方法method
,请检查书籍中作者定义方法method
的位置。
显然@Andreas找到了这个方法,现在我记得了。
使用方法method
,以便在任何对象上调用它时,它在该对象上定义一个方法,该方法的名称是传递给name
的{{1}}参数,该方法的实现是method
函数参数。
您需要在控制台中包含此内容才能使其正常工作。