javascript - 自定义 JS 对象无法正确解析

标签 javascript oop

以下对象是根据 Nicholas Zakas 的“JavaScript 中面向对象编程原理”中的示例构建的。然而,我无法从语法中发现一些错误。当我尝试将其加载到浏览器中时,我在控制台中收到错误:“ReferenceError:owner_idx 未定义”

有人知道如何修复此问题吗?

function Editor() {
    Object.defineProperty(this, "program_idx", {
        get: function() {
            return program_idx;
        },
        set: function(newVal) {
            program_idx = newVal;
        },
        enumerable: true,
        configurable: true
    });

    Object.defineProperty(this, "owner_idx", {
        get: function() {
            return owner_idx;
        },
        set: function(newVal) {
            owner_idx = newVal;
        },
        enumerable: true,
        configurable: true
    });
};

最佳答案

嗯,“owner_idx 未定义”。你为什么不定义它?

function Editor() {

    var program_idx, owner_idx; 

    Object.defineProperty(this, "program_idx", {
        get: function() {
            return program_idx;
        },
        set: function(newVal) {
            program_idx = newVal;
        },
        enumerable: true,
        configurable: true
    });

    Object.defineProperty(this, "owner_idx", {
        get: function() {
            return owner_idx;
        },
        set: function(newVal) {
            owner_idx = newVal;
        },
        enumerable: true,
        configurable: true
    });
};

var e = new Editor();
e.owner_idx = "foo";
console.log(e.owner_idx);

但是如果您的唯一目的是获取/设置属性值(在存储/检索之前不转换它们,或者更改其值影响其他属性),则不需要访问器方法。常规属性就可以很好地工作。

关于javascript - 自定义 JS 对象无法正确解析,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15511964/

相关文章:

javascript - 导出和导入 ECMA6 类

javascript - BlinkID(React-Native)的许可证 key 问题

javascript - 将电子表格值返回给 JavaScript

php - 如何从类中删除一个 PHP 对象?

java - `name()` 与 `getName()` 命名约定?

javascript - 无法从 React vis 图中删除条形之间的间隙

javascript - 为什么使用 `<button>` 作为 `&lt;input type="文件“>` not work, but ` <a>` 的委托(delegate)在 Safari 中有效?

c++ - 为什么我们必须发送const “type ”引用,而不只是将类型名称发送给构造函数

python - 在实例化后向对象添加标志的 pythonic 方法是什么?

javascript - javascript 类应该显式返回某些内容吗?