Javascript js添加封装以修改属性值

Javascript js添加封装以修改属性值,javascript,encapsulation,Javascript,Encapsulation,我有这门课: function level(intLevel) { this.identifier = 'level'; this.intLevel = intLevel; this.strLocation = 'Unknown'; displayLocation : function(locationName){ this.strLocation = locationName; }; this.monsterDelay = 300

我有这门课:

function level(intLevel) {
    this.identifier = 'level';
    this.intLevel = intLevel;
    this.strLocation = 'Unknown';
    displayLocation : function(locationName){
        this.strLocation = locationName;
    };
    this.monsterDelay = 300;
    this.setGrid(50, 24);
    return this;
}
我正在尝试添加e方法来更新strLocation

我不想打电话:

显示位置(“位置”)


这是否正确?

displayLocation
方法是一个函数,只是多了一个属性。属性可以是任何内容:基元类型、对象或函数。因此,您应该像配置其他属性一样对其进行配置:

this.displayLocation = function(locationName){
    this.strLocation = locationName;
};
另一个改进是,您可能希望将可重用方法移动到函数原型,这样就不会在每个实例实例化时重新创建它:

function level(intLevel) {
    this.identifier = 'level';
    this.intLevel = intLevel;
    this.strLocation = 'Unknown';
    this.monsterDelay = 300;
    this.setGrid(50, 24);
}

level.prototype.displayLocation = function(locationName) {
    this.strLocation = locationName;
};
几张便条。您不需要返回
,因为
返回此
是自动暗示的。还建议使用大写字母命名构造函数函数,在您的情况下,
Level
看起来会更好