I think this is a scope problem, but I'm not sure how to fix this. Here is my code: http://jsfiddle.net/9k9Pe/1498/
class FrameCreator{
constructor(){
this.createFrame();
}
createFrame(){
var iframe = document.createElement('iframe');
this.iframe = iframe;
var frameLoaded=this.frameLoaded;
iframe.onload = function () {
frameLoaded();
};
document.body.appendChild(iframe);
}
frameLoaded(){
console.log("frame loaded");
}
}
class CustomFrameCreator extends FrameCreator{
addContent(){
console.log(this); // returns the object
}
frameLoaded(){
console.log(this); // returns undefined
}
}
var frame=new CustomFrameCreator();
frame.addContent();
frameLoaded()
prints undefined, while addContent
prints the object.
How to fix this, so I can have a reference in this when frame is loaded?
Thanks
JavaScript has been a prototypal based language using object prototypes to create object inheritance and code reuse. The new ES6 Class adds a new syntax on top of traditional prototypes. Something I cannot stress enough is the new Class is syntactic sugar on prototypes.
The undefined is a primitive type in JavaScript. So the undefined is a type. And the undefined type has exactly one value that is undefined. JavaScript uses the undefined value in the following situations. When you declare a variable and don’t initialize it to a value, the variable will have a value of undefined. For example:
The add () function returns undefined. It should have returned 30 instead. The problem is that when you create a new line between the return keyword and the returned expression ( a + b ), Javascript compiler automatically inserts a semicolon (;) before the new line. This feature is called automatic semicolon insertion (ASI) in JavaScript.
New Features in ES6 1 The let keyword 2 The const keyword 3 JavaScript Arrow Functions 4 JavaScript For/of 5 JavaScript Map Objects 6 JavaScript Set Objects 7 JavaScript Classes 8 JavaScript Promises 9 JavaScript Symbol 10 Default Parameters More items...
Another alternative to .bind()
is to use ES6 Arrow function to preserve context:
iframe.onload = () => {
this.frameLoaded();
};
class FrameCreator {
constructor() {
this.createFrame();
}
createFrame() {
var iframe = document.createElement('iframe');
this.iframe = iframe;
iframe.onload = () => {
this.frameLoaded();
};
document.body.appendChild(iframe);
}
frameLoaded() {
console.log("frame loaded");
}
}
class CustomFrameCreator extends FrameCreator {
addContent() {
console.log(this); // returns the object
}
frameLoaded() {
console.log(this); // returns the object now
}
}
var frame = new CustomFrameCreator();
frame.addContent();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With