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

1 回答 1

2

只需删除该methods属性并将一个新对象分配prototypeGallery. 还要确保它有一个名为constructorwhich 指向的属性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();
于 2012-06-10T07:48:36.027 回答