我的示例代码:
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
谢谢!