在click事件中调用父函数

Call parent function inside of click event

本文关键字:函数 调用 click 事件      更新时间:2023-09-26

我试图在JavaScript中创建和删除对象的应用程序,但我试图用类来实现它。代码如下所示:

第一个文件:

class GeneralObject {
    constructor(elementName) {
      this.domElement = elementName;
    }
  
    createObject() {
      $(document.createElement('span'))
        .html(this.domElement)
        .appendTo($('#someOtherElement'));
    }
  
    deleteObject() {
      this.domElement.remove();
    }
}

第二个文件:

class SpecificObject extends GeneralObject {
  
  create() {
    
    // call the creator from parent class
    super.createObject();
    
    // create a div
    // i know the div has no expansion
    $(document.createElement('div'))
      .click(function() {
      
        // trying to call the parent function remove
        // here comes the error
        super.removeObject();
      })
      .appendTo($("#someOtherElement"));
  }

我的目标是删除对象,我已经创建,与点击功能,但我不能访问父函数在这个实例。我得到这个错误:

'super'关键字unexpected here

我希望你能告诉我如何在这个点击函数中调用我的父函数。另外,我期待通过"类"关键字对这个实现发表评论,因为我看到到处都只有"原型"的类结构。什么是"正确/更好"的方法?

感谢您阅读这篇文章

super仅在实例方法中可用。你的内部匿名函数不是一个实例方法,所以它不能访问它。

但是,由于使用的是继承,因此可以从this访问该函数。因此,您可以从这个答案中应用解决方案,从内部函数内部访问this

create() {
  var self = this; // get a reference to `this`
  super.createObject();
  $(document.createElement('div'))
    .click(function() {
      self.removeObject(); // `self` is `this` which inherits from `super`
    })
    .appendTo($("#someOtherElement"));
}

因为你只在click函数中执行一个函数,你可以选择将函数引用作为参数传递:

$(document.createElement('div'))
    .click(super.removeObject)
    .appendTo($("#someOtherElement"));

记住它毕竟只是基于原型的:

class SpecificObject extends GeneralObject {
  constructor() {
    super();// make sure to call super since you extend
  }
  create() {
    // createObject is now available on this
    this.createObject();
    // create a div
    // i know the div has no expansion
    $(document.createElement('div'))
      // renamed from removeObject to deletedObject (typo ?) + fatArrow keep scope to the this of the instance
      .click(() => this.deleteObject())
      .appendTo($("#someOtherElement"));
  }
}

我认为你应该使用这样的东西。这将工作得很好。

class SpecificObject extends GeneralObject {
  create() {
    // call the creator from parent class
    super.createObject();
    // create a div
    // i know the div has no expansion
  }
  }
  $(document.createElement('div'))
      .click(function() {
        // trying to call the parent function remove
        // here comes the error
        SpecificObject.removeObject();
      })
      .appendTo($("#someOtherElement"));

不能在document中使用super。Ready函数,因为它现在不是同一个类的函数了。