繁体   English   中英

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

[英]How to call parent method inside a javascript child class

以下是 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() 虽然不确定!!

更新当我浏览答案时,我发现他们中的大多数人建议扩展课程。 但是这里的父类没有名字。 它只是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-to-Child-Components-Events

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM