0

我的示例代码:

    var Person = (function () {
        var __sym = Symbol('Person');

        class Person {
            constructor(name) {
                this[__sym] = { name: name };
            }
            getName() {
                let _this = this[__sym];

                return _this.name;
            }
        }

        return Person;
    }());

    var person = new Person('Hermione');

    console.log(person.name); // undefined
    console.log(person.getName()); // Hermione

在此示例中,我将__sym用作分配给私有数据的键。

我的问题是:如何绑定this[__sym]到 Person 类中的每个方法?

我的真实项目:

let Chatwindow = (function () {
    let __sym = Symbol('Chatwindow');

    let __data = {};

    // for typo
    let __prop = {
        targetUserId: 'targetUserId'
    };

    __data.init = function (...args) {
        let _this = this[__sym];

        let options = args[0];

        // validating the type of 'options' and the properties...

        // just get what I need
        _this[__prop.targetUserId] = options[__prop.targetUserId];

        (async () => {
            let messages = await __data.getMessagesAsync.call(_this);

            // my goal:
            // let messages = await __data.getMessagesAsync();
        })();
    };
    __data.getMessagesAsync = function () {
        let _this = this;

        let promise = new Promise(function (done) {
            // create model before sending
            let model = { [__prop.targetUserId]: _this[__prop.targetUserId] };

            // sending...

            done();
        });

        return promise;
    };

    class Chatwindow {
        constructor() {
            this[__sym] = {};
        }
        set init(value) {
            return __data.init;
        }
        get init() {
            return (...args) => __data.init.call(this, ...args);
        }
    }

    return Chatwindow;
}());

每次调用方法时,我都必须使用call(_this)函数来绑定键,如下所示:

let messages = await __data.getMessagesAsync.call(_this);

之后,在方法内部,我可以使用属性getMessagesAsync分配给私有数据。this

我想要实现的目标:我想在方法内一次绑定所有init方法。我怎样才能做到这一点?

像这样的东西:

__data.getMessagesAsync.oncall = function () {
    // bind this with this[__sym]
};

然后,

__data.getMessagesAsync(); // no need to pass anymore

谢谢!

4

2 回答 2

1

您可以使用箭头函数,因此您将确保上下文(this)每次都相同(无论从哪里调用箭头函数,this 都将指向父 this)

__data.getMessagesAsync = () => {
    let promise = new Promise((done) => {
        // create model before sending
        let model = { [__prop.targetUserId]: this[__prop.targetUserId] };

        // sending...

        done();
    });

    return promise;
}
于 2018-10-12T07:01:57.373 回答
0

在 javascript 中, usingfunction_name.bind(o)允许您创建一个其上下文this绑定到 object的新函数o

您想要的是创建一个新功能:

__data.boundMessagesFunction = __data.getMessagesAsync.bind(_this);

现在您可以致电:

let messages = await __data.boundMessagesFunction();
于 2018-10-12T07:02:39.930 回答