How to access this function in my object?

2019-08-14 17:56发布

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?

2条回答
三岁会撩人
2楼-- · 2019-08-14 18:32

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.

查看更多
狗以群分
3楼-- · 2019-08-14 18:46
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());
查看更多
登录 后发表回答