我查看了有关在Javascript中使用self
的几个问题,我不相信其中任何一个都能回答我的问题-具体来说就是如何在ES6中创建self
class
(不是ES5,并且不能在Angular中使用)。
我正在尝试在ES6类的回调函数中使用self
。我使用的唯一框架是jQuery。我知道我需要使用self
,但是我不知道如何在ES6类中创建self
变量。
<!-- BEGIN HTML -->
<div id="Header">
I want header-message.html to render here...
</div>
<div id="Footer">
I want footer-message.html to render here...
(But currently, both HTML chunks will appear here)
</div>
<script src="call/to/jquery.js"></script>
<script type="module" src="main.js"></script>
<!-- END HTML -->
// BEGIN main.js
import {ContentAsServiceClass} from './contentAsAService.js';
$(function() {
$('<div id="HeaderContent"></div>').appendTo('#Header');
let headerContent = new ContentAsServiceClass(
{
$htmlTargEl: $('#HeaderContent'),
htmlFileName: 'header-message.content.html'
}
);
headerContent.renderContent();
$('<div id="FooterContent"></div>').appendTo('#Footer');
let footerContent = new ContentAsServiceClass(
{
$htmlTargEl: $('#FooterContent'),
htmlFileName: 'footer-message.content.html'
}
);
footerContent.renderContent();
});
// END main.js
// BEGIN contentAsAService.js
export let ContentAsServiceClass = class {
constructor(
{
// defaults:
$htmlTargEl = null,
htmlFileName = ''
} = {
// override defaults:
$htmlTargEl: $htmlTargEl,
htmlFileName: htmlFileName
}
) {
// assign values to instance of object:
this.$htmlTargEl = $htmlTargEl,
this.htmlFileName = htmlFileName;
self = this;
// assigns `self` to `window` object - which I DON'T want,
// and will not work here! But how do I assign `this` to `self` in an ES6 class?
// Assigning to `var` (`var self = this`) does not work here.
}
appendHtmlContent(response) {
// I know I need to use `self` here.
if(!response || typeof response !== 'string') {
return false;
}
$(self.$htmlTargEl).append(response);
}
getHtmlContent() {
$.get(
'http://localhost/content/my-bucket/' + this.htmlFileName
).then(
this.appendHtmlContent
);
}
renderContent() {
this.getHtmlContent();
}
}
export default ContentAsServiceClass;
// END contentAsAService.js