We all know that the JS variable has a scope concept, so you can use this attribute to define the private field, and the initialization of the private field is mainly through the constructor.
For example, the following defines a read-only field first
function ListCommon2 (Afirst)
{
var first=afirst;
This. Getfirst=function () defines a privileged method to access the Read field {return a
;}
Listcommon2.prototype.do2=function ()
{
var field= this. GetFirst ();//Read field alert in the instance method using the privileged method
;
}
function test () {
//test code
var t2=new ListCommon2 ("Boiling water 2");
T2.do2 ();//
}
See more highlights of this column: http://www.bianceng.cnhttp://www.bianceng.cn/webkf/script/
Of course, if you need a method to modify a field, you can also define a privileged method that is similar to reading a field.
As follows:
function ListCommon2 (Afirst)
{
var first=afirst;
This. Getfirst=function () defines a privileged method to access the Read field {return a.
}
This. Setfirst=function (NewValue)//defines a privileged method to set the field
{return
first=newvalue
}
} Listcommon2.prototype.do2=function ()
{
var field= this. GetFirst ();//Read field alert in the instance method using the privileged method
;
}
function test () {
//test code
var t2=new ListCommon2 ("Boiling water 2");
T2. Setfirst ("test");//Reset field
t2.do2 ();//
}
So the definition field can define local variables in the constructor, using the privileged method as a way to read and set fields, which can be accessed indirectly through privileged functions.