1

I have a javascript getter method like so:

function passTags()
{
var tags = document.getElementById('tags').value;


    this.getTag=function()
    {
        return this.tags;
    }
}

How do i call it?

4
  • I'd say getTag(), see javascriptgarden.info/#function.this. Commented Apr 3, 2011 at 16:25
  • @Jakub, getTag is not defined for anyone outside the passTags() function so it won't be recognised. i need to use dot notation i suppose but not sure about exact syntax required Commented Apr 3, 2011 at 16:27
  • Well if you call passTags() then getTag() should be defined in global scope. Commented Apr 3, 2011 at 16:28
  • @Jukub, surely you will agree that the point is to call passTags and to access its tag variable via the getter so i need to do it in one go...not in sequence as suggested Commented Apr 3, 2011 at 16:31

2 Answers 2

3

Looks like you've set up a constructor function, so it would be like so

var t = new passTags;
t.getTag();

this.tags is not defined though, so t.getTag() will return undefined. If you meant for it to return the value of tags then change it to

function passTags() {
    var tags = document.getElementById('tags').value;
    this.getTag = function() {
        return tags;
    }
}

bear in mind though that the value captured will not update once the constructor function has executed, as this example will demonstrate. One more recommendation would be to use Pascal case for the function name so that it is clear that it is a constructor function.

The way that you have your code set up at the moment though, if it wasn't intended to be a constructor function then you would first have to execute passTags function. This would define a function in global scope, getTag, that could then be executed. This will return undefined however as this.tags is undefined.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Russ, that's great help
0

You shouldn't define tags as var tags = ... but as this.tags = ...

-- edit

Russ's solution is 'better': tags is now private.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.