How to create privacy with the use of bind()
我将一个对象文本传递到一个名为
这行吗?还有别的事情要考虑吗?在我测试之前需要一些反馈。
以下是相关的代码片段。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 | /*$A.supportP ** ** ** */ $A.supportP = function (o, not_singleton) { var oo key; SupportList[o.Name] = {}; if (not_singleton) { // ignore this section } else { // *look here - isFunc returns true if a function for (key in o) { if ((key !== '_p') && (isFunc(o[key])) { oo[key] = o[key].bind(o); } else if (key !== '_p') { oo[key] = o[key]; } else { // private (_p) - anything to do here? } } return oo; } }; /*$A.test ** ** ** */ var singleton_object = $A.supportP({ _p: 'I am private', Name: 'test', publik_func: function () { // this will refer to this object so that it can access _p // this._p is accessible here due to binding } }, false); |
Will this work?
是的,您可以通过
Are there other things to consider?
您正在克隆对象。然而,它的方法无法访问它——它绑定到"旧"对象,该对象的属性不会反映对副本的更改。我不确定这是出于设计还是出于偶然。
为了严格的私有性,需要使用带有局部变量的闭包。不能将属性设为私有。
1 2 3 4 5 6 7 8 9 10 | var singleton_object = (function() { var _p = 'I am private'; // local variable return { Name: 'test', publik_func: function () { // this will refer to this object so that it can access the properties // _p is accessible here due to closure, but not to anything else } }; }()); // immediately-executed function expression |
另一种解决方案,使用两个不同的对象(一个隐藏对象),这些对象被传递到一个框架方法中:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | function bindPrivates(private, obj) { for (var key in obj) if (typeof obj[key] =="function") obj[key] = obj[key].bind(obj, private); return obj; } var singleton_object = bindPrivates({ p: 'I am private' }, { Name: 'test', publik_func: function (_) { // this will refer to this object so that it can access"public" properties // _.p, a"private property" is accessible here due to binding the private // object to the first argument } }); |