Javascript prototype chain and privileged Methods
function ClassA() { var value=4; this.getValue= function() { return value; } this.setValue= function(value) { this.value=value; } } var instance= new ClassA(); document.write(instance.getValue()); classA.setValue(1); document.write(instance.getValue()); document.write(instance.value);
Output result: 4, 4, 1.
The reason is: var value is a private variable, which is not the same value as this. value.
Next, we will analyze how to create an object instance and access the private variables.
1. instance attributes and prototype attributes
When a javascript Object creates an instance, the instance attributes and methods can be assigned to the instance only through this in the constructor. If you want to create shared attributes or methods, you can share them through the prototype chain.
Create shared attributes:
Function ClassA () {var value = 4; this. getValue = function () {return value;} this. setValue = function (value) {this. value = value ;}} ClassA. prototype. value = 1; // shared value var instance1 = new ClassA (), // instance2 = new ClassA (); consloe. log (instance1.value); // 1 consloe. log (instance2.value); // 1 console. log (ClassA. value); // undefined
Can the private attribute value in ClassA () be accessed through ClassA. value? The answer is no.
We analyze the identifier search in the object instance. When an instance looks for an attribute, there are two steps:
(1). Search for the instance attributes of the instance.
(2) If the instance properties cannot be found, the prototype of the object will be found along the prototype chain.
If ClassA. value cannot be found in the instance attribute of ClassA, the prototype chain will be searched. ClassA is an Object instance, so it will find the Object. prototype. value. The value is undefined.
2. Access to private variables
We know that javascript does not have block-level scope, but we can simulate block-level scope through functions. The variables in block-level scopes are called private variables. Private variables, which cannot be accessed externally. We can
Generate a privileged method (privileged method: the method that can access private variables). The privileged method here is this. getValue (). Create a method by using constructors to create a privileged method.
Another way to create a privileged method is static.
Function ClassA () {var value = 4; this. getValue = function () {return value;} this. setValue = function (value) {this. value = value;} ClassA. getValue = function () {// return value of the static method ;}}