The javascript function namespace simulation getter, setter

function namespace

In javascript, function can also have their own namespace
for example, this code:

1
2
3
4
5
6
7
8
function () {
return 'I am A';
}

A.hello = 'hello!';

console.log(A());
console.log(A.hello);

We can get the following in the console:

1
2
I am A
hello!

Can be found even if A is declared as a function, it can still be the same object as assign them to other attribute, A direct call itself or function to its original function

getter、setter

In javascript, this would call it an object, you can refer here
so we can combine the characteristics of naming written like this

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
function () { The let the Name = 'John' ; the let Gender = 'MALE' ; < large column in javascript function namespace analog getters, the setter span = class "Line">   function F (



  ) {
}

f.Name = function(_) {
if (!arguments.length) {
return Name;
}
Name = _;
return this;
}

f.Gender = function(_) {
if (!arguments.length) {
return Gender;
}
Gender = _;
return this;
}

return f;
}

const a = A();

console.log(a.Name());
console.log(a.Gender());

Here we define the function of two variables in A Name, Gender
and A were used in the two function as access their getter and setter
if we do not pass any arguments to a.Name and a.Gender, it will be they got through two local variables a, therefore console will be printed here:

1
2
john
male

And if we have passed argument, such as this:

1
2
console.log(a.Name('alice').Name());
console.log(a.Gender('female').Gender());

These two functions will be used as a setter, and will return to continue the call f other variables
This is because we are both a function of the return this, so we again got the call he objects f, it can be console obtained:

1
2
alice
female

Here we see can function as a general namespace to use, in addition to through this can implement getter, setter to access this namespace variables

Guess you like

Origin www.cnblogs.com/lijianming180/p/12326500.html