How to access this function in my object?

霸气de小男生 提交于 2020-01-15 11:39:08

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!