How to implement private properties in JavaScript write Class (i) _javascript skills

Source: Internet
Author: User

Previously discussed how to write in JavaScript. However, private implementations are not discussed. Look at this article.

We know that the implementation of JS private property is the essence of Var + closure. As follows

Copy Code code as follows:

function person (n, a) {
Public
THIS.name = n;
Private
var age = A;
This.getname = function () {
return this.name;
}
This.getage = function () {
return age;
}
}

The test follows that age is private and can not be obtained using the dot operator, but only with the GetName method.
Copy Code code as follows:

var p = new Person (' Jack ', 23);
Console.log (P.age); Undefined
Console.log (P.getage ()); 23

The above is not unusual, we use a tool function to implement.
Copy Code code as follows:

/**
* @param {String} className
* @param {Function} classimp
*/
function $class (className, Classimp) {
function Clazz () {
if (typeof this.init = = "function") {
This.init.apply (this, arguments);
}
}
Classimp.call (Clazz.prototype);
Window[classname] = Clazz;
}

Write a class
Copy Code code as follows:

$class (' person ', function () {
Private properties are defined in this
var age = ';
This.init = function (n, a) {
Common properties hanging on this, initializing
THIS.name = n;
Private Property Initialization
age = A;
};
This.getname = function () {
return this.name;
};
This.getage = function () {
return age;
}
});

New an Instance Object
Copy Code code as follows:

var p = new Person (' Jack ', 23);
Console.log (P.name); Jack has a common use point operator to get
Console.log (P.age); Undefined private can not get through the dot operator
Console.log (P.getage ()); 23 private age can only be acquired by means of a common method getage

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.