I'm new to JavaScript. New as far as all I've really done with it is tweaked existing code and wrote small bits of jQuery.
Now I'm attempting to write a "class" with attributes and methods, but I'm having trouble with the methods. My code:
function Request(destination, stay_open) { this.state = "ready"; this.xhr = null; this.destination = destination; this.stay_open = stay_open; this.open = function(data) { this.xhr = $.ajax({ url: destination, success: this.handle_response, error: this.handle_failure, timeout: 100000000, data: data, dataType: 'json', }); }; /* snip... */ } Request.prototype.start = function() { if( this.stay_open == true ) { this.open({msg: 'listen'}); } else { } }; //all console.log's omitted
The problem is, in Request.prototype.start
, this
is undefined and thus the if statement evaluates to false. What am I doing wrong here?
A variable that has not been assigned a value is of type undefined . A method or statement also returns undefined if the variable that is being evaluated does not have an assigned value. A function returns undefined if a value was not returned .
myVariable is declared and not yet assigned with a value. Accessing the variable evaluates to undefined . An efficient approach to solve the troubles of uninitialized variables is whenever possible assign an initial value. The less the variable exists in an uninitialized state, the better.
One way to define a class is using a class declaration. To declare a class, you use the class keyword with the name of the class ("Rectangle" here).
The value undefined means value is not assigned & you don't know its value. It is an unintentional absence of value. It means that a variable has been declared but has not yet been assigned a value. The value null indicates that you know that the field does not have a value.
I just wanted to point out that sometimes this error happens because a function has been used as a high order function (passed as an argument) and then the scope of this
got lost. In such cases, I would recommend passing such function bound to this
. E.g.
this.myFunction.bind(this);
How are you calling the start function?
This should work (new is the key)
var o = new Request(destination, stay_open); o.start();
If you directly call it like Request.prototype.start()
, this
will refer to the global context (window
in browsers).
Also, if this
is undefined, it results in an error. The if expression does not evaluate to false.
Update: this
object is not set based on declaration, but by invocation. What it means is that if you assign the function property to a variable like x = o.start
and call x()
, this
inside start no longer refers to o
. This is what happens when you do setTimeout
. To make it work, do this instead:
var o = new Request(...); setTimeout(function() { o.start(); }, 1000);
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