Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/435.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在javascript中声明受保护的变量_Javascript_Oop - Fatal编程技术网

在javascript中声明受保护的变量

在javascript中声明受保护的变量,javascript,oop,Javascript,Oop,如何声明受保护的变量。让我举个例子 // Constructor function Car(){ // Private Variable var model; } // Public variable Car.prototype.price = "5 Lakhs"; // Subtype function Indiancar(){ } // Prototype chaining Indiancar.prototype = new Car(); // Instantiati

如何声明受保护的变量。让我举个例子

// 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();

在这里,我希望有一个变量可以作为ic.variabl访问,它也存在于汽车类中。

您可以这样做:

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());
假设我正确理解了你的问题


编辑:使用真正的“private”变量进行更新。

有一种方法可以在JavaScript中定义受保护的变量:

javascript中的构造函数可以返回任何对象(不一定是这样)。可以创建一个构造函数,返回一个代理对象,其中包含指向“real”实例对象的“real”方法的代理方法。这听起来可能很复杂,但事实并非如此;以下是一段代码片段:

var MyClass = function() {
    var instanceObj = this;
    var proxyObj = {
        myPublicMethod: function() {
            return instanceObj.myPublicMethod.apply(instanceObj, arguments);
        }
    }
    return proxyObj;
};
MyClass.prototype = {
    _myPrivateMethod: function() {
        ...
    },
    myPublicMethod: function() {
        ...
    }
};

好的是,如果我们定义一个命名受保护方法的约定,代理创建可以自动化。我创建了一个小库,它可以做到这一点:

正如前面所说,javascript没有受保护的变量

在写这个问题的10年里,它已经成为一件事,对javascript中的OOP感兴趣的人应该看看它!它确实支持受保护的变量

话虽如此,我还是想向大家致敬,并提供一种使用纯javascript模拟受保护变量的方法,因为这是谷歌的顶级搜索结果,而在撰写本文时,其他两个答案并不符合要求

//在匿名函数中声明对象以限制访问。
var objectRefs=(函数(){
//这是我们要从中继承的对象。
函数基(参数1,受保护){
var public=this;
var protected=protected |{};
var private={};
//声明一些变量
public.shared=“任何人都可以访问此!”;
protected.inherited=“这是受保护的”;
private.secretVar=“儿童无法访问此项。”;
//让我们试试几个函数。
public.foo=函数(){
//我们可以在这里访问受保护的和私有的函数
//如果我们把它连接到原型上,这是不可能的。
console.log(protected.inherited);
console.log(private.secretVar);
private.secret();
};
protected.bar=函数(){
//需要注意的一件事是:之后调用的私有函数
//构造无法通过“this”访问对象。这是
//我将其分配给“public”var,这一事实掩盖了这一点。
//更多阅读:https://stackoverflow.com/q/20279484/3658757
console.log(public.shared);
};
private.secret=函数(){
//protected.bar中的相同警告也适用于此处。
console.log(public.shared);
};
}
//继承自基础
派生函数(参数1,受保护){
var public=this;
var protected=protected |{};
var private={};
//继承(准备好魔术了吗?)
Base.call(this,param1,protected);
//因为我们将对“protected”对象的引用作为参数传递
//对于基础对象,它已将其所有受保护的
//变量。我们现在可以在此处访问这些变量:
//输出“这是受保护的”
console.log(protected.inherited);
//我们还可以访问受保护的功能:
protected.bar();
//我们甚至可以覆盖受保护的变量和函数。
protected.inherited=“新值!”;
//我们无法访问属于Base的私有变量。
//这失败了:
//console.log(private.secretVar);
}
//我们不想允许公共访问构造函数,因为
//将让外部代码传入一个“受保护”变量。相反,我们创建新的
//对象,这些对象接受除“protected”之外的所有参数,并从
//目标对象。
返回{
基本:函数(参数1){
Base.call(this,param1);
},
派生:函数(参数1){
调用(this,param1);
}
};
})();
//为清晰起见,将构造函数分配给变量。
var Base=objectRefs.Base;
var-Derived=objectRefs.Derived;
//这就是构造对象的方式。
var newDerived=新衍生(“参数1”);
//公共功能是无障碍的。
newDerived.foo();
//不支持受保护的函数。这些失败:
//newDerived.bar();
//newDerived.protected.bar();
那真有趣!这种结构使受保护的变量以您期望的方式运行:继承对象可以访问它们,但从外部无法访问它们

以下是上述代码在Typescript中的外观,以供参考:

类基
{
//声明一些变量
public shared:string=“任何人都可以访问此文件!”;
受保护继承:string=“这是受保护的”;
private secretVar:string=“子级无法访问此项。”;
构造函数(param1:string){
//我们没有使用param1,它只是一个例子。
//如果我们不需要任何构造函数代码,我们可以省去这个。
//请注意,Typescript具有类型检查功能(因此得名)
}
//让我们试试几个函数。
public foo():void{
console.log(this.inherited)
console.log(this.secretVar)
这个。秘密();
}
受保护条():无效{
console.log(this.shared);
}
私人秘密():无效{
console.log(this.shared);
}
}
类派生的扩展基{
构造函数(param1:string){
超级(参数1);
//输出“这是受保护的”
log(this.inherited);
//我们还可以访问受保护的功能:
这个.bar();
//我们甚至可以覆盖受保护的变量和函数。
this.inherited=“新值!”;
}
}
//这就是构造对象的方式。
var newDerived=新衍生(“参数1”);
//公共功能是无障碍的。
newDerived.foo();
//不支持受保护的函数。这失败了:
//newDerived.bar();
从结构上看,这一点要清楚得多。在编码时,如果试图从ob外部访问受保护的变量,则会出现错误