rpanske rpanske - 2 months ago 6
Javascript Question

Call parent function inside of click event

I've tried to make an application in JavaScript that simply creates and deletes an object, but i try to implement it with classes. The code looks like the following :

My first file :



class GeneralObject {

constructor(elementName) {
this.domElement = elementName;
}

createObject() {
$(document.createElement('span'))
.html(this.domElement)
.appendTo($('#someOtherElement'));
}

deleteObject() {
this.domElement.remove();
}
}





My second file :



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"));
}





My goal is it to delete the object, i've created, with the click function, but i can't access the parent function in this instance. I get this error :


'super' keyword unexpected here


I hope you can tell me how to call my parent function in this click function. Also i look forward to an comment about this implementation via the "class" keyword, because i see everywhere only class constructs with "prototype". What is the "correct / better" way ?

Thank you for reading this post

Answer

super is only available in instance methods. Your inner anonymous function is not an instance method, so it does not have access to it.

However, since you're using inheritance, the function will be accessible from this. Therefore, you can apply the solution from this answer to access this from inside an inner function.

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"));
}

Since you're only executing a single function inside that click function, you can alternatively pass the function reference as a parameter:

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