首页 > 解决方案 > ES3 的 Javascript getter/setter

问题描述

我有以下功能,我正在尝试在 Photoshop 中实现(使用 Javascript ES3 编写脚本)。我怎么能把它写成与 ES3 兼容?

function VParabola(s){
    this.cEvent = null;
    this.parent = null;
    this._left = null;
    this._right = null;
    this.site = s;
    this.isLeaf = (this.site != null);
}

VParabola.prototype = {
    get left(){
        return this._left;
    },
    get right(){
        return this._right;
    },
    set left(p){
        this._left = p;
        p.parent = this;
    },
    set right(p){
        this._right = p;
        p.parent = this;
    }
};

标签: javascriptphotoshop-scriptecmascript-3

解决方案


您可以Object.defineProperty在构造函数中使用,例如

function VParabola(s){
    this.cEvent = null;
    this.parent = null;
    var left = null;
    var right = null;
    this.site = s;
    this.isLeaf = (this.site != null);

    Object.defineProperty(this, 'right', {
        get: function () {
            return right;
        },
        set: function (value) {
            right = value;
        }
    })

    Object.defineProperty(this, 'left', {
        get: function () {
            return left;
        },
        set: function (value) {
            left = value;
        }
    })

 }

推荐阅读