问题
I have a function object:
var myObj=function(){
};
myObj.prototype = {
availableColor: function(i){
return "red_"+i;
}
getColor: function(){
var c = availableColor('3'); //Error: availableColor is not a function
...
}
}
When I call availableColor(i)
inside getColor()
function, I got error availableColor is not a function....
I also tried to use var c = this.availableColor('3');
and
var self=this
in the constructor, then var c = self.availableColor('3');
But, none of these help. what is the reason?
回答1:
var myObj={
availableColor: function(i){
return "red_"+i;
},
getColor: function(){
var c = this.availableColor('3');
}
}
EDIT
Another approach:
var myObj=function(){
};
myObj.prototype.availableColor = function(i){
return "red_"+i;
};
myObj.prototype.getColor = function(){
var c = this.availableColor('3');
return c;
};
b = new myObj();
document.write(b.getColor());
回答2:
If you just want to add methods to myObj, just do:
myObj.availableColor = function(i){
return "red_"+i;
}
myObj.getColor = function(){
var c = this.availableColor('3');
}
The way you use prototype
will make myObj
an constructor: var o = new myObj()
. myObj
won't have those methods.
来源:https://stackoverflow.com/questions/5701503/how-to-access-this-function-in-my-object