Home  >  Article  >  Web Front-end  >  Visibility description of JavaScript object members_javascript tips

Visibility description of JavaScript object members_javascript tips

WBOY
WBOYOriginal
2016-05-16 18:44:281283browse

The visibility definitions of JavaScript object construction can be divided into the following types:
1. Private properties (private properties)

Define the scope of variables in object construction through the var keyword. This variable can only be accessed within the scope of the object's constructor method. For example:

Copy code The code is as follows:

function VariableTest()
{
var myVariable;//private
}
var vt = new VariableTest();
vt.myVariable;//an undefined exception will occur here

 2, Private methods
Similar to private properties, they can only be accessed within the scope of the object constructor. For example:
Copy code The code is as follows:

function MethodTest()
{
var myMethod = function()//private
{
alert("private method");
}
this.invoke = function()
{
//can be accessed to myMethod
myMehtod();
}
}
var mt = new MethodTest();
mt.myMethod(); // Error. Using trycatch, you can catch the "object does not support this property or method" exception
mt.invoke();

 3. Public properties (public properties)
There are two ways to define public attributes:
(1) Define through the this keyword. For example:
Copy code The code is as follows:

function PrivilegedVariable()
{
this.variable = "privileged variable";
}
var pv = new PrivilegedVariable();
pv.variable;//return "privileged variable"

 (2 ) is defined through the prototype of the constructor method. For example:
Copy code The code is as follows:

function PublicVariable(){}
PublicVariable .prototype.variable = "public variable";
var pv = new PublicVariable();
pv.variable;//return "public variable"

 4, public Methods (public methods)
Similarly, there are two ways to define public methods.
 
  (1) Defined by this keyword. (2) Defined by the prototype of the construction method.
Omit here. . . . . . . . . . .
5. Static properties
Properties added directly to the object construction method cannot be accessed by the object instance and can only be used by the construction method itself. For example:
Copy code The code is as follows:

function StaticVariable(){}
StaticVariable .variable = "static variable";
var sv = new StaticVariable();
sv.variable;//Return "undefined"
StaticVariable.prototype.variable;//Return "undefined"
StaticVariable.variable;//Return "static variable"

6. Static methods (static methods)
Methods added directly to the object construction method cannot be object instances Access can only be used by the constructor itself.
Code omitted. . . . . . . .
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn