I am having trouble with the following code:
function Class() {
var self = this;
var $div = $('<div/>');
$div.data('obj',self);
this.get = function() {
return $div;
}
}
var x = new Class();
var $y = x.get();
The problem is that I store the object “self” data using jQuery’s .data() function, but I cannot seem to access it later. What is going wrong?
EDIT:
The following is the code I should actually be asking about:
function Class() {
var self = this;
var $div = $('<div/>');
$div.data('obj',self);
var sample = "S";
this.get = function() {
return $div;
}
}
var x = new Class();
var $y = x.get();
alert($y.data('obj').sample); // <-- This returns 'undefined'
$divisn’t a property ofthis— rather, it’s simply a variable in an accessible scope:Despite similar names and values, these is no relation between the
$divvariables:If you want a variable to be a property of the object, you have to define it on
this: