javascript 在javascript中声明受保护的变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7533590/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
declaring protected variable in javascript
提问by indianwebdevil
How do i declare protected variable. Let me give an example here
我如何声明受保护的变量。让我在这里举个例子
// Constructor
function Car(){
// Private Variable
var model;
}
// Public variable
Car.prototype.price = "5 Lakhs";
// Subtype
function Indiancar(){
}
// Prototype chaining
Indiancar.prototype = new Car();
// Instantiating Superclass object
var c = new Car();
// Instantiating subclass object
var ic = new Indiancar();
in this I would like to have a variable that is accessible as ic.variabl that is also present in car class.
在这方面,我希望有一个可作为 ic.variabl 访问的变量,该变量也存在于汽车类中。
回答by Tejs
You would do something like this:
你会做这样的事情:
var Base = function()
{
var somePrivateVariable = 'Hello World';
this.GetVariable = function()
{
return somePrivateVariable;
};
this.SetVariable = function(newText)
{
somePrivateVariable = newText;
};
};
var Derived = function()
{
};
Derived.prototype = new Base();
var instance = new Derived();
alert(instance.GetVariable());
instance.SetVariable('SomethingElse');
alert(instance.GetVariable());
Assuming I understood your question correctly.
假设我正确理解了你的问题。
EDIT: Updating with true 'private' variable.
编辑:使用真正的“私有”变量进行更新。
回答by slobo
There is a way to define protected variables in JavaScript:
有一种方法可以在 JavaScript 中定义受保护的变量:
A constructor function in javascript may return any object (not necesserily this). One could create a constructor function, that returns a proxy object, that contains proxy methods to the "real" methods of the "real" instance object. This may sound complicated, but it is not; here is a code snippet:
javascript 中的构造函数可以返回任何对象(不一定是this)。可以创建一个构造函数,它返回一个代理对象,该对象包含“真实”实例对象的“真实”方法的代理方法。这听起来可能很复杂,但事实并非如此;这是一个代码片段:
var MyClass = function() {
var instanceObj = this;
var proxyObj = {
myPublicMethod: function() {
return instanceObj.myPublicMethod.apply(instanceObj, arguments);
}
}
return proxyObj;
};
MyClass.prototype = {
_myPrivateMethod: function() {
...
},
myPublicMethod: function() {
...
}
};
The nice thing is that the proxy creation can be automated, if we define a convention for naming the protected methods. I created a little library that does exactly this: http://idya.github.com/oolib/
好处是代理创建可以自动化,如果我们定义命名受保护方法的约定。我创建了一个小库,它就是这样做的:http: //idya.github.com/oolib/