开发者

Default Function/Value for JavaScript Class

Is it 开发者_Go百科possible to set something of a default/fallback function for a JavaScript class?

var a = new function() {

  this.b = function() {
    return "B";
  }

  return "A";
}

In this example, I'd want to see B when executing alert(a.b()), and A for alert(a) alone.


var a = new function() {    
  this.toString = function() { return "Four Loko comes in 8 different flavors."; };
  this.valueOf = function() { return "Four Loko comes in 8 different flavors."; };
  this.b = function() { return "Added! :3"; };
}
alert(a);
alert(a.b());

If you overwrite the toString method of an object you can get it to return whatever you want.

Although you may be trying to return literal values from a constructor. You can only return objects from a constructor.

You may also want to overwrite .valueOf


Your question and your sample code are a little vague but this might be what you're looking for:

function A() {
    this.b = function () {
        return "Added! :3";
    }
}

var a = new A();
alert( a.b() );

which would be better if you do it this way:

function A() {}

A.prototype.b = function () {
    return "Added! :3";
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜