gpt4 book ai didi

javascript - 私有(private)对象属性

转载 作者:行者123 更新时间:2023-11-30 18:17:11 24 4
gpt4 key购买 nike

我有一个 RequireJs 模块,它实例化了另一个模块并代理了它的一些方法。我现在想隐藏模块实例本身,只允许通过代理方法进行访问。

define(['mediator'], function(Mediator) {

var Proxy;

Proxy = function(prefix) {
this.prefix = prefix;
this.mediator = new Mediator();
};

Proxy.prototype.on = function(event, callback, context) {
this.mediator.subscribe(this.prefix + event, callback, context || this);
};

Proxy.prototype.off = function(event, callback, context) {
this.mediator.unsubscribe(this.prefix + event, callback, context || this);
};

Proxy.prototype.trigger = function() {
arguments[0] = this.prefix + arguments[0];
this.mediator.trigger.apply(this.mediator, arguments);
};

return Proxy;

});

require(['proxy'], function(Proxy) {

var proxy = new Proxy('sample:');

// this access is secured and bound to the prefix
// I cannot mess up with other events which do not belong to me
proxy.on('log', function(message) { console.log(message); });
proxy.trigger('log', 'hi hello');

// unfortunately there still would be a hack to leave my event scope
proxy.mediator.trigger('outerscope:test', 'blabla');

});

如您所见,可以访问代理原型(prototype)的内部使用的中介对象并将其搞砸......

我现在想以某种方式隐藏调解器实例,但不知道在哪里。我可以将它存储在 requirejs 模块回调内的某个普通变量中,但这不适用于 requirejs 并且可能导致重叠。

那我还能做什么呢?

更新:

define(['mediator'], function(Mediator) {

var Proxy;

var mediator = new Mediator();

Proxy = function(prefix) {
this.prefix = prefix;
};

Proxy.prototype.on = function(event, callback, context) {
mediator.subscribe(this.prefix + event, callback, context || this);
};

Proxy.prototype.off = function(event, callback, context) {
mediator.unsubscribe(this.prefix + event, callback, context || this);
};

Proxy.prototype.trigger = function() {
arguments[0] = this.prefix + arguments[0];
mediator.trigger.apply(this.mediator, arguments);
};

return Proxy;

});

require(['proxy'], function(Proxy) {

var proxy = new Proxy('sample:');
proxy.on('log', function(message) { console.log(message); });

});

最佳答案

这是一个典型的Javascript闭包封装变量的例子。您需要将中介实例定义为与 Proxy 处于同一范围内的局部变量。这将允许 Proxy 对象通过闭包访问 Mediator,但会将 Mediator 与定义回调之外的代码隔离开来。所以像这样:

define(['mediator'], function(Mediator) {

// Make mediator local scope variable
var mediator = new Mediator(),

Proxy = function(prefix) {
this.prefix = prefix;
};

Proxy.prototype.on = function(event, callback, context) {
mediator.subscribe(this.prefix + event, callback, context || this);
};

// ... rest of the code

return Proxy;

});

关于javascript - 私有(private)对象属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12986285/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com