如何在JavaScript中'mirror'一个属性?

How to 'mirror' a property in JavaScript?

我可能没有使用正确的术语。我想实现的是 'mirror' 或 'sync' javascript 中的一个变量。我有以下代码:

class myClass {
    constructor(elem) {
        this.text = elem.innerText;
    }
}

这不会更改 eleminnerText 属性。我将如何配置变量 [s] 以使它们 'mirror' 彼此?

P.S 我很难用谷歌搜索这个,因为我不知道我想要实现的目标的术语。

你想要的是所谓的数据绑定。 Javascript 中的变量本身并不是这样操作的。你必须用 getter/setter 方法包装它们。

所以它看起来像这样:

var myElem = Sizzle("#myElem");

mirror('myVar', function(myVar){
    myElem.innerText = myVar;
});

mirror('myVar', 'foo');

镜像的实现如下所示:

var __data__ = {};
var __bindings__ = {};
function mirror(name, value){
    // if no value is passed in
    // get the existing value
    if(!value){
        return __data__[name];
    }

    // if the "value" is a function
    // register it to the list of
    // functions that get called when
    // the value changes. Also known
    // as a listener.
    if(typeof value == 'function'){
        var func = value;

        // if there's no existing list
        // for this value, create one
        if(!__bindings__[name]){
            __bindings__ = [];
        }

        // if the data already exists
        // go ahead and fire this function
        // immediately
        if(__data__.hasOwnProperty(name)){
            func(__data__[name]);
        }

        __bindings__[name].push(func);
        return;
    }

    // if we've made it this far, we're setting
    // the value of our variable
    __data__[name] = value;

    // if there's a list of functions (listeners)
    // call each of them passing in the value that
    // we just set
    if(__bindings__.hasOwnProperty(name)){
        __bindings__[name].forEach(function(func){
            func(__data__[name]);
        });
    }
}

在js中,就像在其他程序语言中一样,分配原始类型变量,不创建对它的引用。 所以你可能会写这个来设置 innerHTML:

var myElem = Sizzle("#myElem");
myElem.innerText = "foo";
var myElem = Sizzle("#myElem");
var obj = {
    set myVar(text) {
        myElem.innerText = text;
    },
    get myVar() {
        return myElem.innerText;
    }
};
obj.myVar = "foo";

您可以使用 setters and getters,但您需要将绑定变量置​​于对象内。

编辑:

从技术上讲,即使是全局变量也属于 window 对象,所以这应该可行:

var myElem = Sizzle("#myElem");
Object.defineProperty(window, 'myVar', {
    set: function(text) {
        myElem.innerText = text;
    },
    get: function() {
        return myElem.innerText;
    }
});
myVar = "foo";  // works assuming that we are using global scope
                // i.e. myVar isn't overridden in local scope
window.myVar = "foo"; // will work regardless

更新:

问题已更改,因此这是更新后的答案:

class myClass {
    constructor(elem) {
        Object.defineProperty(this, 'text', {
            set: function(text) {
                elem.innerText = text;
            },
            get: function() {
                return elem.innerText;
            }
        });
    }
}