组织对象原型的更好方法是什么

What's a better way to organise the object's prototype?

本文关键字:更好 方法 是什么 原型 对象      更新时间:2023-09-26

这就是我尝试组织原型的方式:

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

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();​

只需删除 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();