I have a javascript getter method like so:
function passTags()
{
var tags = document.getElementById('tags').value;
this.getTag=function()
{
return this.tags;
开发者_JAVA百科}
}
How do i call it?
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
.
You shouldn't define tags
as var tags = ...
but as this.tags = ...
-- edit
Russ's solution is 'better': tags
is now private.
精彩评论