base.js与沙盒 [英] base.js with sandboxing

查看:97
本文介绍了base.js与沙盒的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用base.js的实现:http://ejohn.org/blog/simple-javascript-inheritance/



I试图将其与沙盒相结合以获得私有变量。例如:



I''m using an implementation of base.js from here: http://ejohn.org/blog/simple-javascript-inheritance/

I attempted to combine this with sandboxing to get "private" variables. For example:

// Sandbox.
(function () {

var privateVar;

myClass = Class.extend({
    init: function (bindingOptions) {
        privateVar = 0;
    },

getPrivateVar: function() {
    return privateVar;
},

setPrivateVar: function(value) {
    privateVar = value;
});
})();



但是,当我尝试制作2个实例时,privateVar当然具有相同的值。例如:




However, when I try to make 2 instances, of course the "privateVar" has the same value. For example:

var class1 = new myClass();
var class2 = new myClass();
class1.setPrivateVar(5); // now both class1 and class2 report privateVar as "5"



有没有什么办法可以使用这种方法来获取私有变量,而不需要求助于this._privateField?


Is there any way to get private variables using this methodology that are scoped to the object without resorting to "this._privateField" ?

推荐答案

之后进一步的研究,这里的答案是不可能的。



参考: http://robertnyman.com/2008/10/21/javascript-inheritance-experimenting-with-syntax-alternatives-and- private-variables / [ ^ ]



原因是如果你使用我上面概述的沙盒方法,任何私有变量宣布将是圣ATIC。但是,方法可以成功隐藏和工作。
After further research, the answer here is that it isn''t possible.

Reference: http://robertnyman.com/2008/10/21/javascript-inheritance-experimenting-with-syntax-alternatives-and-private-variables/[^]

The reason is that if you use the sandboxing methodology I outlined above, any "private" variable declared will be static. Methods, however, can successfully be hidden and work.


如果你想要特定于实例的私有变量,





If you want instance specific private variables,


function ClassConstructor(...) {
var that = this;
var membername = value;
function privatememthod(...) {...}

}





你有特定于实例的私有变量membername&私有方法privatemethod。



访问外部方法:





you have instance specific private variable membername & private method privatemethod.

Access for external methods:

function ClassConstructor(...) {
var that = this;
var membername = value;
function privatememthod(...) {...}

return {
  getPrivareMember: function(){
       return membername;
  }
}
}


这篇关于base.js与沙盒的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆