javascript - js添加封装修改属性值

标签 javascript encapsulation

我有这门课:

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('位置');

这是正确的吗?

最佳答案

displayLocation 方法是一个函数,只是一个属性。属性可以是任何东西:基本类型、对象或函数。所以你应该像配置其他属性一样配置它:

this.displayLocation = function(locationName){
    this.strLocation = locationName;
};

另一个改进是,您可能希望将可重用方法移动到函数原型(prototype),这样它就不会在每个实例实例化时都重新创建:

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;
};

一些笔记。您不需要返回 this,因为 return this 是自动隐含的。还建议使用大写字母命名构造函数,在您的情况下 Level 会更好看。

关于javascript - js添加封装修改属性值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29163832/

相关文章:

java - jquery.get 和 servlet

javascript - 遍历所有节点并在 Javascript 中生成键和值

javascript - react 路由器传递数据

c++ - 为什么人们要编写返回非常量引用的私有(private)字段 getter?

javascript - Chrome 扩展 : how to dock extension's html page to current web page?

javascript - 从一系列按钮返回值

java - 如何从子类的子类获取在父类(super class)中实例化的对象的字段

c++ - 封装和指向对象的指针

Java:封装库的自动方式

oop - OO 设计 - 对象向间接持有它的类提出问题