js中的class继承怎么使用?-灵析社区

正确计算方式

js中的class继承怎么使用? 父类Parent中有个fetch函数,我想再次包装下,只对入参做些修改,其他的全部继承父类,但是一直失败 class Parent { constructor() { } fetch = (data) => { console.log(1, data) } } class Child extends Parent { constructor(props) { super(props) } fetch = (data) => { if (data) { data.name = 'test' } console.log(2, data) return super.fetch(data) } } `Parent`是个组件`fetch`是箭头函数尽量不做修改,上面这种写法会报错`super.fetch is not afunction`,原因是`super`不支持在箭头函数中使用,但是改成常规写法 fetch() { } 这种方式又没法重写`Parent`中的`fetch`函数,请问这种情况该怎么处理? class Child extends Parent { constructor(props) { super(props) } fetch = (data) => { if (data) { data.name = 'test' } const item = new Parent() return item.fetch(data) } } 这样写可以么?

阅读量:12

点赞量:0

问AI
class Parent { constructor() {} fetch = (data) => { console.log(1, data); }; } class Child extends Parent { constructor(props) { super(props); } // 改写 fetch = ((superfetch) => (data) => { if (data) { data.name = "test"; } console.log(2, data); superfetch(data); })(this.fetch); } 做了修改,应该可以满足你的方式。 参考的 => "https://stackoverflow.com/a/52823577/10378232" (https://link.segmentfault.com/?enc=dLKNHUUt%2F2yuTA9C8jbU5w%3D%3D.YYg7Vl5Z4pYBUZGF5ab9AhYVrhLd1KCS%2BIpT77fbNGE%2B8l8CpNdgAW1eLR7x8eLR)