gpt4 book ai didi

javascript - 在javascript中声明 protected 变量

转载 作者:行者123 更新时间:2023-12-02 06:21:57 25 4
gpt4 key购买 nike

我如何声明 protected 变量。让我在这里举个例子

// 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中声明 protected 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7533590/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com