2012-06-10 60 views
-1

这是我如何尝试组织原型:组织对象原型的更好方法是什么?

但是,我必须编写额外的“方法”属性来访问原型的功能是相当低效的。

var Gallery = function(name) { 
    this.name = name; 
} 

Gallery.prototype.methods = { 
    activeCnt: 0, 
    inc: function() { 
     this.activeCnt++; 
    }, 
    dec: function() { 
     this.activeCnt--; 
    }, 
    talk: function() { 
     alert(this.activeCnt); 
    } 
} 


var artGallery = new Gallery('art'); 
var carGallery = new Gallery('car'); 
artGallery.methods.inc(); 
artGallery.methods.talk(); 
carGallery.methods.talk();​ 
+1

这是什么问题?您想做什么? – gdoron

+0

你的第一句话似乎表明它跟随着它,但它不在那里...?此外,这不是一个真正的代码审查和建议网站。根据FAQ,我认为这不是一个有效的问题。 –

回答

2

只需卸下methods属性,并指定新对象的Galleryprototype对象。另外请确保它有一个名为constructor的房产,该房源指向Gallery。代码如下:

var Gallery = function (name) { 
    this.name = name; 
} 

Gallery.prototype = { 
    activeCnt: 0, 
    inc: function() { 
     this.activeCnt++; 
    }, 
    dec: function() { 
     this.activeCnt--; 
    }, 
    talk: function() { 
     alert(this.activeCnt); 
    }, 
    constructor: Gallery 
}; 


var artGallery = new Gallery('art'); 
var carGallery = new Gallery('car'); 

artGallery.inc(); 
artGallery.talk(); 
carGallery.talk(); 
相关问题