在JavaScript中从父方法调用子方法
Calling child method from parent in JavaScript
我有一个JavaScript类,我想通过创建一个子类来覆盖父方法。然而,我正在努力找出如何从父方法的上下文中调用子方法。
这是我父母的精简版:
// "rules" is a global hash
function ForumFilter() {
this.scanText = function(title, body) {
// Save 'this' context, as each() overwrites it
var that = this;
// This is jQuery each()
$.each(rules, function(ruleName, rule) {
// rule.search is a regex
var match = rule.search.test(body);
if (match)
{
that.isPassed = false;
// ** I'd like to call a child method here,
// ** but it only calls the method in this class
that.setRuleFailed(ruleName);
}
});
}
this.setRuleFailed = function(ruleName) {
this.failedRules.push(ruleName);
}
}
这是我对孩子的尝试:
ForumFilterTest.prototype = new ForumFilter();
ForumFilterTest.prototype.setRuleFailed = function(ruleName) {
// Call parent
ForumFilter.setRuleFailed(ruleName);
// Record that this one has triggered
this.triggered.push(ruleName);
}
下面是我从一个子实例调用我的父方法:
var scanner = new ForumFilterTest();
scanner.scanText("Hello", "Hello");
因此,在scanText
(只存在于父级中(中,它可以调用setRuleFailed
,后者应该调用ForumFilterTest
中的版本,后者反过来调用它覆盖的类。因此,正如它的名字所暗示的,为了测试的目的,我试图向父方法添加一个行为,所以如果ForumFilter
是单独实例化的,我当然希望使用父方法。
在更好地理解您的问题后,以下是我实际提出的更改。具体来说,您需要将ForumFilter
方法移动到其prototype
。这将允许ForumFilterTest
方法显式引用ForumFilter
方法。
步骤1:将ForumFilter
方法移动到其prototype
。
function ForumFilter() {}
ForumFilter.prototype.scanText = function(title, body) {
// Save 'this' context, as each() overwrites it
var that = this;
// This is jQuery each()
$.each(rules, function(ruleName, rule) {
// rule.search is a regex
var match = rule.search.test(body);
if (match)
{
that.isPassed = false;
// ** I'd like to call a child method here,
// ** but it only calls the method in this class
that.setRuleFailed(ruleName);
}
});
};
ForumFilter.prototype.setRuleFailed = function(ruleName) {
this.failedRules.push(ruleName);
};
步骤2:需要时明确引用ForumFilter
"父"方法:
// "child class" implementation
function ForumFilterTest() {}
ForumFilterTest.prototype = new ForumFilter();
ForumFilterTest.prototype.setRuleFailed = function(ruleName) {
// Call parent
ForumFilter.prototype.setRuleFailed.call(this, ruleName);
// Record that this one has triggered
this.triggered.push(ruleName);
};
相关文章:
- 如何在webView,Android中从@JavascriptInterface方法调用Javascript
- javascript从子方法调用父方法
- 我应该返回一个类似console.log()的方法调用吗
- NodeJS-从同一文件中的另一个方法调用一个方法
- 使用restangular save方法调用put与post时的控件
- 从实例方法调用实例方法
- Node.js-异步方法调用问题
- Jquery事件绑定获胜'当作为方法调用时不起作用,但当直接在控制台中调用时会起作用
- 向模板实例变量传递调用方法调用的结果时出现异常
- jQuery 方法调用了两次
- 不能从 Backbone.View 的方法调用 Backbone.collection 的方法,其中包含 require
- 组合 onLayout 的方法调用
- lodash/下划线 - 使用绑定与方法调用和方法保持未绑定
- 从公共方法调用模块的私有函数
- 如何对 jqGrid 的 loadComplete 和 onSelectRow 进行基因预和后方法调用
- 完全限定的 JavaScript 方法调用
- 为什么我在 Angular JS 中收到两个方法调用
- 如何在从排序方法调用参数时将其传递给回调
- 使用两种不同的方法调用方法
- 如何在 javascript 中更改方法调用的全局范围