First Look:
Copy Code code as follows:
var objjson={
OP1: ' Objjson option1 ',
Fn1:function () {
Alert (THIS.OP1)
}
}
In this form of declaration, you can access the internal properties directly via OBJJSON.OP1 or OBJJSON.FN1 (), which is no problem. But if this is the case:
Copy Code code as follows:
var objfn=function () {
this.op1= ' OBJFN.OP1 ';
This.op2=function () {
Alert (THIS.OP1)
};
}
So if you are directly objfn.op1 or OBJFN.OP2 () to access the internal attributes, it is not, because this time he is not an object.
So we need to instantiate him.
Copy Code code as follows:
var inst=new objfn ();
alert (INST.OP1);
INST.OP2 ();
So you can get the value you want.
If you want to copy the JSON-form object, it's simple, but there's a problem:
Copy Code code as follows:
var Newone=objjson;
newone.op1= ' changed ';
Alert (' Objjson.op1 ');
You will find that the value of the OP1 in the original object has also changed. However, if the second method of object declaration is used, then the modification is only within the instance and does not affect other instances.
So static objects like JSON are suitable for writing some commonly used libraries, have his own namespace, who will not interfere with who, and easy to use.
The "public" private property of the constructor
We'll make a modification to the above constructor:
Copy Code code as follows:
var objfn=function () {
var pri1= ' private variable ';
this.op1= ' public variable ';
This.op2=function () {
Alert (pri1+ ', ' +this.op1);
};
};
var o=new objfn ();
Alert (typeof o.pri1+ ', ' +typeof o.op1);//undefined,string
O.OP2 ()//private variable, public variable
Private variables are not allowed to be accessed outside the object, and all typeof are undefined. Let's look at the private method access:
Copy Code code as follows:
var objfn=function () {
var pri1= ' private variable ';
var pri2=function () {
THIS.OP2 ();
};
this.op1= ' public variable ';
This.op2=function () {
Alert (pri1+ ', ' +this.op1);
};
This.acpri=function () {
Pri2.call (this);
};
};
var o=new objfn ();
O.ACPRI ()//private variable, public variable
Note that because of the closure characteristics of JavaScript, we need to use call to pass the context of the program through the public Method Acpri () Pri2, but this looks too faint to wrap around a bit:
Copy Code code as follows:
var objfn=function () {
var my=this;
var pri1= ' private variable ';
var pri2=function () {
MY.OP2 ();
};
this.op1= ' public variable ';
This.op2=function () {
Alert (pri1+ ', ' +this.op1);
};
This.acpri=function () {
Pri2. ();
};
};
var o=new objfn ();
O.ACPRI ()//private variable, public variable
The final result, of course, remains unchanged.
Reprint please keep the following information
Author: North Jade (TW: @rehawk)