![](/img/trans.png)
[英]ReactJS onClick event inside map function, then call parent's function
[英]Call parent function inside of click event
我試圖用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")); }
我的目標是使用click函數刪除我創建的對象,但是在這種情況下我無法訪問父函數。 我收到此錯誤:
'super'關鍵字在這里意外
希望您能告訴我如何在此click函數中調用父函數。 我也期待通過“ class”關鍵字對此實現進行評論,因為我到處都只能看到帶有“ prototype”的類構造。 什么是“正確/更好”的方式?
感謝您閱讀這篇文章
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"));
您不能使用super inside document.ready函數,因為它現在不屬於該類的函數,並且不具有該類特定對象的相同作用域。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.