woojoo666
woojoo666

Reputation: 7921

Javascript using this.function results in 'has no method' error

I have this simple Javascript object that calls its own prototype method in one of its local methods. [SEE MY EDIT]

var Obj = function() {
    function inner() {
        this.exported();
    }

    this.exported = function() {
        alert("yay!");
    };
};

var test = new Obj();
Obj.exported();

However, I get the error TypeError: Object function() {...} has no method 'exported'. Any idea how this should be done?

EDIT: whoops, just realized I never called inner(), but thanks Patrick for answering that part anyways. Here is a better example

var Obj = function() {

    this.exported = function() {
        inner();
    };

    function inner() {
        this.yay();
    }

    this.yay = function() {
        alert("yay!");
    };
};

var test = new Obj();
test.exported();

I get TypeError: Object [object global] has no method 'exported'

Upvotes: 0

Views: 45

Answers (2)

Suman Bogati
Suman Bogati

Reputation: 6349

should be used

test.exported();

instead of

Obj.exported();

You should invoked exported() method over the test object, not over the Obj constructor.

UPDATE

After reached inside the function inner(){...}. this is refers to global window not Obj, so pass the actual object this from inner(this) and do invoke export() from that passed object into function inner(cthis){...}, something like.

function inner(cthis) {
    //----------^--get Obj on here
    cthis.exported();
}

this.exported2 = function() {
    inner(this);
   //------^--pass Obj from here
};

DEMO

Upvotes: 3

Patrick Evans
Patrick Evans

Reputation: 42736

to call exported you need to call it off the variable you assigned the instance to:

test.exported();

Also for the inner function you cannot use this there to access the Obj object as it refers to window. save a reference to this and then use that to call the function

var Obj = function() {
    var _this = this;
    function inner() {
        _this.exported();
    }

    this.exported = function() {
        alert("yay!");
    };
};

Upvotes: 2

Related Questions