【问题标题】:Defining Javascript class prototype methods定义 Javascript 类原型方法
【发布时间】:2011-06-02 19:58:15
【问题描述】:

我一开始是这样定义一个类的:

function mapTile(nx,ny)
{
    //members
    this.x = nx;
    this.y = ny;

    //methods
    this.prototype.visible = function(){return true;};
    this.prototype.getID = function(){return y*tiles_per_line+x;};
    this.prototype.getSrc = function(){return 'w-'+this.getID+'.png';}
};

当我尝试创建对象时会引发异常:

t=new mapTile(1,1)
TypeError: Cannot set property 'visible' of undefined

在 Chromium 中并在 Firefox 中静默失败(使用 firebug)

这工作正常:

function mapTile(nx,ny)
{
    //members
    this.x = nx;
    this.y = ny;
};

//methods
//this.prototype.xx=1;
mapTile.prototype.visible = function(){return true;};

在主体内部实现原型方法的正确方法是什么?

【问题讨论】:

    标签: javascript oop prototype


    【解决方案1】:

    在主体内部实现原型方法的正确方法是什么?

    您可能不喜欢这个答案:不要在正文中定义它们,因为每次构造函数为该对象运行时都会重新定义它们。在声明它们之后使用objectType.prototype... 定义它们。

    原型方法是专门在所有实例之间共享的,您正在做的是介于两者之间的某个地方,您要么希望它们在特定于该实例的内部声明,如下所示:

    function mapTile(nx,ny)
    {
        //members
        this.x = nx;
        this.y = ny;
    
        //methods
        this.visible = function(){return true;};
        this.getID = function(){return y*tiles_per_line+x;};
        this.getSrc = function(){return 'w-'+this.getID+'.png';}
    }
    

    或者分享在原型外面,像这样:

    function mapTile(nx,ny)
    {
        //members
        this.x = nx;
        this.y = ny;
    }
    mapTile.prototype.visible = function(){return true;};
    mapTile.prototype.getID = function(){return y*tiles_per_line+x;};
    mapTile.prototype.getSrc = function(){return 'w-'+this.getID+'.png';}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-05-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多