给定类 A 和类 B,其中类 B 继承自类 A ...
// Define class A
dojo.declare("mynamespace.A",null,{
myMethodA: function() { this.myMethodB() }
});
// Define class B
dojo.declare("mynamespace.B",mynamespace.A,{
myMethodB: function() {}
});
在A类(父类)的范围内调用this.myMethodB()是否合法? 我在一个软件中看到过这个,但我不明白。我知道在 Java 中,这是不可能的,除非您将 A 类型转换为 B。但是 dojo 有什么不同吗?
最佳答案
这个问题的流行语是this.inherited(arguments); 你的问题是调用一个不在当前继承范围内的方法 - 并且会被真正的面向对象的程序员称为无效的..但是它是可能的(仍然)因为加载器在全局范围内声明了一切,例如您可以通过mynamespace.X 访问任何模块,然后添加 prototype.theMethod。
一旦您像在 mynamespace.B 中那样继承,A 和 B 的所有功能都在“this”范围内。它就像东西的合并散列,比如说 A 中的所有方法和变量都设置了实例 B[key] = property A[key]
。
但是,如果您遇到覆盖,其中属性为“类”A 和 B 的原型(prototype) - 在声明/构造链中有一种机制允许调用“ super ”(或父类,按照您的符号) .
对于特殊的属性构造函数,总是如此,继承冒泡[period]。
对于任何只声明一次的方法,如果它不是继承的方法,您就不能自己调用它 - 然后可以通过“this”访问它
对于任何具有覆盖的方法,函数 'this.inherited(arguments);'将把你向上发送,一个 tick 到当前的被调用者父类。看看扩展的 fiddle here
var AClass = dojo.declare("mynamespace.A", null, {
constructor: function(args) {
this.overriddenMethod();
},
overriddenMethod: function() {
}
});
var BClass = dojo.declare("mynamespace.B", [AClass], {
constructor: function() { },
overriddenMethod: function() {
// call super before anything else is processed in this method
// by placing following call you can control function callflow
this.inherited(arguments);
}
});
// will call A.constructor, then A.overriddenMethod
new AClass();
// will call B.constructor, A.constructor, B.overriddenMethod and then
// A.overriddenMethod via the call to super
// in B.overriddenMethod which A.constructor
// calls (note that A.constructor callflow 'aims' B.override not A.override)
new BClass();
关于javascript - 在 dojo 中使用 this 通过父类访问子方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10658652/