调用影子原型方法的更简单/更好的方法
Simpler / better way to call shadowed prototype method?
我正在用JavaScript编写对象层次结构,当我在对象中对对象的父对象上的方法进行阴影处理时,我想调用该方法。
例如:
var Base = function Base(msg) {
this.msg = msg;
}
Base.prototype.log = function(){
console.log("base log: " + this.msg);
}
var Sub = function Sub(msg) {
Base.call(this, msg);
}
Sub.prototype = Object.create(Base.prototype);
Sub.prototype.log = function() {
console.log("sub log");
this.__proto__.__proto__.log.call(this); // This works but __proto__
Object.getPrototypeOf(Object.getPrototypeOf(this)).log.call(this); // This works but is verbose
super.log(); // This doesn't work
}
var sub = new Sub('hi');
sub.log();
请看Sub.prototype.log
函数底部的三行——有更好的方法来完成我要做的事情吗?
第二行是我能想到的最好的一行,但非常冗长!
super
没有定义,显然它不起作用。
你可能想试试:
Sub.prototype.log = function() {
console.log("sub log");
Base.prototype.log.call(this);
}
另一种方法是使用以下方法来继承类:
function extend(Child, Parent) {
var F = function() { };
F.prototype = Parent.prototype;
Child.prototype = new F();
// better to make it static (better practice in OOP world)
// e.g. Child.super = ...,
// but in your case:
Child.prototype.super = Parent.prototype;
}
这里有一个例子:
// ..
extend(Sub, Base);
Sub.prototype.log = function() {
console.log("sub log");
this.super.log.call(this);
}
在ES6
:的情况下
class Base {
constructor(msg) {
this.msg = msg;
}
log(){
console.log("base log: " + this.msg);
}
}
class Sub extends Base {
constructor(msg) {
super(msg);
}
log() {
console.log("sub log");
super.log();
}
}
var sub = new Sub('hi');
sub.log();
如果您想保留原始方法而不使用名称Base
,您可以在更改它之前使用闭包捕获它。
(function() {
var superLog = Sub.prototype.log;
Sub.prototype.log = function() {
console.log("sub log");
superLog();
};
})();
这样就不依赖于如何从Base
继承。
附带说明:您要查找的术语是"覆盖"基本方法。
相关文章:
- 有没有更好的动手、具体的方法来学习Javascript
- 为什么不推荐使用“with”?是否有更好或其他方法可以“下降”到对象的命名空间
- 在JavaScript中拆分日期字符串的更好方法是什么
- 设置嵌套对象属性的更好方法
- 用Javascript重新格式化复杂文本日期字符串的更好方法
- 有没有比在app.js上绑定模块名称更好的方法来动态加载视图模型和视图以显示模态
- 什么'这是从第三个函数上的async 1st函数获得结果的更好方法
- 将数组从javascript格式化为php的更好方法,反之亦然
- jquery:将动画绑定到滚动条位置的更好方法
- 有更好的方法吗?(递归解析HTML unicode实体)
- 使用较少代码隐藏和显示选择菜单内容的更好方法是什么?javascript
- 编写if-else语句的更好方法
- 我能从“;输入“;事件是否有更好的方法来跟踪文本更改
- 有没有更好的方法可以测量从Ajax调用返回数据所需的总时间
- 有没有更好的方法将音频与视频同步(只需将其放在视频中即可)
- 调用影子原型方法的更简单/更好的方法
- 有没有更好的方法来编写这个Show/hide JQuery代码
- AngularJS:有没有比指定的方法更好的方法来实现这一点
- 哪种验证方法更好
- 哪一种定义变量的方法更好?为什么?