Marlene75
Marlene75

Reputation: 29

Javascript Object: a function or method in an attribute

I am a trying to put the result of a method in an attribute, but I keep getting the error: "Uncaught TypeError: Object [object DOMWindow] has no method 'ppp'"

This is my simple code:

var ttt = {
    ddd: 'I said '+ this.ppp() + '!!!',


    ppp:function(){
        return 'ok';
    }
};
alert(ttt.ddd)

Thx for your help :)

Upvotes: 2

Views: 202

Answers (3)

Mark Withers
Mark Withers

Reputation: 1482

The problem is that in your code 'this' is referring to the window object.

To get around this, you could turn ttt into an auto-executing function

i.e

var ttt = function() {
function ppp(){
     return 'ok'   
}

return {
    ddd: 'I said '+ ppp() + '!!!',
    ppp: ppp
}
}();

At this point you can still use your original code to alert ddd

alert(ttt.ddd)

To see this in action go to http://jsfiddle.net/aCeqt/

Upvotes: 1

David
David

Reputation: 8650

There is no block scope in javascript (only function scope), so this.ppp() refers to the global scope (which means it will be looking on the window object for ppp), as it is not inside a function.

You could rewrite it as follows:

var ttt = (function () {
    var innerttt = {
        ddd: function () {
            return 'I said ' + this.ppp() + '!!!';
        },
        ppp: function(){
            return 'ok';
        }
    };

    return innerttt;
})();

alert(ttt.ddd())

This will give ddd the scope it needs to call ppp.. which means the this part of this.ppp() will be looking inside the function for ppp

More info on scope and closures.. http://robertnyman.com/2008/10/09/explaining-javascript-scope-and-closures/

Upvotes: 1

Allen.M
Allen.M

Reputation: 41

var ttt = {
    ddd:function(){
        return  'I said '+ this.ppp() + '!!!';
    },


    ppp:function(){
        return 'ok';
    }
};
alert(ttt.ddd())

This is OK . The code you write , ttt.ddd is a string , the 'this' is window object in browser.

Upvotes: 2

Related Questions