[英]Javascript Override parent method with child method
How i can override parent method on child ? 我怎么能覆盖孩子的父方法? Is javascript have something like parent::method(); 是javascript有像parent :: method();
var Parent = function(){
this.myMethod(){
//Some code here
};
}
var Child = function(){
Parent.call(this);
this.myMethod(){
//Some code here
//and then run parent method
};
}
Updated There is better way than do that (not ES6)?: 更新有比这更好的方法(不是ES6)?:
var Parent = function ()
{
this.myMethod()
{
this.extedMyMethod()
//Some code here
};
this.extedMyMethod()
}
var Child = function ()
{
Parent.call(this);
this.extedMyMethod()
{
//Some code which expand parent method
};
}
PS If i do like @Suren Srapyan suguest webpack will convert to proper non ES6 ? PS如果我喜欢@Suren Srapyan suguest webpack将转换为适当的非ES6?
With ES6 class syntax inheritance you can do it via super
calls. 使用ES6类语法继承,您可以通过super
调用来完成。
class Parent{ method(){ console.log('Parent !!!'); } } class Child extends Parent{ constructor(){ super(); } method(){ console.log('Child !!!'); super.method(); } } var child = new Child(); child.method();
UPDATED 更新
You need also to use polyfill for different browsers 您还需要将polyfill用于不同的浏览器
This is a native approach: 这是一种原生方法:
Person = function (name) { this.name = name; this.sayBang = function() { console.log("Bang!"); } console.log("i'm a Person"); } Programmer = function (name) { Person.call(this,name); this.sayBang = function() { console.log("I'm hungry!"); } console.log("i'm a Programmer"); } var marco = new Programmer("Marco"); console.log(marco); marco.sayBang();
You can create new instances or return functions to make them accessible 您可以创建新实例或返回函数以使其可访问
var Parent = function(){
return () => {
alert("parent");
};
};
var Child = function(){
this.myMethod = function(){
alert("child")
Parent()();
}
};
var foo = new Child();
foo.myMethod();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.