dotnetN00b
dotnetN00b

Reputation: 5131

Why can't I access this variable in javascript?

I created an object and I want to access the variables in that object. But everytime I run this, testThis and whatThis variables are undefined. I'm not sure why this is happening.

/* HTML above */
<script type="text/javascript">
    var formData;
    var dataClickTest;

    var FormRowData = function () {
        var self = this;

        self.someValue = "I am visible. Look Here!";

        self.frds = new Array();

        self.addRowData = function (ctrlData) {
            self.frds.push(ctrlData);
        }

        self.convertData = function (rowData) {
            var hi = rowData[0].attr('data-ctrltypeid');
            var hello = "hi";
        }
    }



    function postBackPart(div_id) {

        formData = $('#' + div_id).find('input, select').filter('[name*=".InputtedData"]');

        var testThis = FormRowData();      /* error here */
        var whatThis = testThis.someValue; /* error here */     

        $.ajax({
            url: '/TestEdit/Sections',
            type: 'POST',
            data: formData,
            success: function (result) {
            }
        });

        return false;
    }
</script>

</body>
</html>

Upvotes: 0

Views: 80

Answers (3)

Esailija
Esailija

Reputation: 140230

Since you are not actually using prototypes, you can skip new entirely:

var FormRowData = function () {
    var self = {};

    self.someValue = "I am visible. Look Here!";

    self.frds = new Array();

    self.addRowData = function (ctrlData) {
        self.frds.push(ctrlData);
    }

    self.convertData = function (rowData) {
        var hi = rowData[0].attr('data-ctrltypeid');
        var hello = "hi";
    }

    return self;
}

Is equivalent to your code without requiring new

Upvotes: 1

Quentin
Quentin

Reputation: 943571

FormRowData doesn't have a return statement and you aren't invoking it with the new keyword that would treat it as a constructor function, so it returns undefined.

It looks like you intend it to be used as a constructor function so:

var testThis = new FormRowData(); 

That should resolve both problems.

Upvotes: 1

tletnes
tletnes

Reputation: 1998

var testThis = new FormRowData();

Upvotes: 1

Related Questions