本文介绍了在javascript中声明受保护的变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我如何声明受保护的变量。让我举个例子
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();
在这里我希望有一个可以作为ic.variabl访问的变量,它也存在于汽车类。
in this I would like to have a variable that is accessible as ic.variabl that is also present in car class.
推荐答案
你会做这样的事情:
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.
编辑:使用真正的'私人'变量进行更新。
Updating with true 'private' variable.
这篇关于在javascript中声明受保护的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!