如何在javascript子类中调用父方法



以下是vue组件js文件的代码。

(假设vue组件js文件是Class(

export default { -----> this is the parent, it is a component & it doesn't have a name!
name: "mapping",
components: {},
props: ["data"],
data() {
},
methods: {
parentMethod() {} ---->> this is the parent method. I want to call this inside the Rect class
},
mounted() {
class Rect { -----> this is the child class, 
constructor() {
this.parentMethod() // -> this is the parent method. how can I do this?
}
// call parent methods (i.e. component's) inside this class
//or something like this.
this.parentMethod() // -> this is the parent method. how can I do this?
}

}

正如你所看到的,我正在vue-js组件类中的挂载钩子中创建一个名为Rect的类。

我想要的是在这个Rect类中调用父组件的方法。

我怎样才能做到这一点?

更新

我不是在其内部扩展父组件类。我只是在父组件类中定义一个名为Rect的新类。所以我不认为我可以呼叫super()。但不确定!!

UPDATE当我浏览答案时,我发现大多数答案都建议扩展类。但是这里的父类没有名称。只是export default {} in vue

&我也不确定我是否能够在自身内部扩展父类以在自身内部创建一个新类。

注意

要求是从父类的子类(即在父类中定义=>在父体中定义(的类中/内部调用父方法希望这有意义!!

当您创建一个新类时,您将更改该类中的this。所以你需要给这个类一个对其父类的引用:


mounted() {
const parentRef = this; // reference to the parent instance
class Rect { 
constructor() {
parentRef.parentMethod() 
}
...
parentRef.parentMethod() // -> this is the parent method
}
}

检查扩展和超级关键字:

//Inheritance
//Parent class (superclass)
class Animal {                            
constructor(name) {           
this._name = name;
this._behavior = 0;
}
get name() {
return this._name;
}
get behavior() {
return this._behavior;
}   
incrementBehavior() {
this._behavior++;
}
} 
//Child class (subclass)
class Cat extends Animal {          // The extends keyword makes the methods of the animal class available inside the cat class.     
constructor(name, usesLitter) {
super(name);                    // The super keyword calls the constructor of the parent class.
this._usesLitter = usesLitter;
}
get usesLitter() {
return this._usesLitter;
}
}
const bryceCat = new Cat('Bryce', true);
console.log(bryceCat.name);             //Output: Bryce
console.log(bryceCat.usesLitter);       //Output: true

在Vue中,您希望从由父组件处理的子组件发出事件,而不是直接从子组件调用父组件方法。

请参阅https://v2.vuejs.org/v2/guide/components.html#Listening-到子组件事件

最新更新