Js Object-Oriented Programming (2): attributes and closures

Source: Internet
Author: User

The previous blog explains some basic concepts and usage of js objects. This blog explains js attributes: Public attributes, private attributes, and privileged methods.


If you have been familiar with java, public attributes, private attributes, and privileged methods (that is, methods that can access and set Private attributes), let's see how to implement them in js?


1. Public attributes

First, we can see that the first layer of public is accessible to everyone. The attribute that is open to the outside is relative to the private attribute:

function Person(name,age){this.name=name;this.age=age;this.getName=function(){return this.name;}this.getAge=function(){return this.age;}}var josh=new Person('josh','25')console.log(josh.name);  //joshconsole.log(josh.getName()); //josh

We have defined a Person object named josh here. Let's create two other Person objects through the new method.

var Eric=new Person('Eric','25');var mongo=new Person('mongo','23');console.log(Eric.name);  //Ericconsole.log(mongo.name);  //monge
Here, every time we create an object, all the code in Person will be copied, resulting in a waste of memory. You can solve this problem by defining methods that are common to the same class object, therefore, we need the prototype keyword here.

Literally, prototype can be understood as "property to type", that is, type attributes. For a class of attributes, take the Person defined above, that is, for the methods or attributes shared by objects such as Person, we need to modify the code above.

function Person(name,age){this.name=name;this.age=age;}Person.prototype.getName=function(){return this.name;}Person.prototype.getAge=function(){return this.age;}var josh=new Person('josh','25')var Eric=new Person('Eric','25');var mongo=new Person('mongo','23');console.log(josh.getName()); //joshconsole.log(Eric.name);  //Ericconsole.log(mongo.name);  //monge

Therefore, public methods or attributes can also be understood as the methods or attributes added through the prototype of the constructor. The constructor here is Person. Because js does not have the concept of classes, therefore, we use constructors to create new objects, and the attribute methods defined by prototype are shared for this type. For example, static methods or attributes in java classes are shared by a class.


2. Private attributes

Based on the encapsulation feature of objects, we do not want to expose all variables to the outside world. Therefore, taking the Person object above, we define this in the attribute definition. the name is changed to var name, so the public attribute that can be accessed by the outside world is changed to private attribute, and the access result for the attribute is also changed to undefined.

Function Person (name, age) {// this. name is changed to var namevar name = name; var age = age;} var josh = new Person ('Josh ', '25') var Eric = new Person ('Eric ', '25'); var mongo = new Person ('mongo', '23'); console. log (josh. name); // undefinedconsole. log (Eric. name); // undefinedconsole. log (mongo. name); // undefined

Why is the object property changed from public to private when this. name is changed to var name? First, let's take a look at the this keyword. this indicates the objects in the current property:
function Person(name,age){this.name=name;this.age=age;}
The above code is replaced by the following section, you can understand, that is, first define a Person empty constructor, and then define the person object, add the name and age attributes dynamically based on the characteristics of the person property.

function Person(){}var person=new Person();person.name='josh';person.age='25';

How is the private attribute changed to var name implemented? Here, we need to design several important basic concepts for JavaScript objects, including scope, context, and closure.

First, the scope should be known if you have been familiar with a programming language. The scope is the scope within which variables can be referenced. Java is block-level. It is defined in if and while blocks and can only be used in blocks; if you want to have a larger scope, you can define the method at the beginning for the whole method to use, but it cannot be used outside the method; or you can define the class level, can be referenced in the entire class.

In js, the scope is function-level, that is, the variables defined in the function cannot be referenced outside the function, and the function plays a role in defining the scope. In the preceding example, the access to the josh. name attribute becomes undefined.

Function Person (name, age) {// this. name is changed to var namevar name = name; var age = age;} var josh = new Person ('Josh ', '25'); console. log (josh. name); // undefined

Next, explain the context. The context indicates the environment where the function or object is located. This environment contains some variables, objects, or functions. View a picture with the concept of Scope



In this figure, the person object can access the variables, objects, or functions in the context, while the variables in the context cannot access the name attribute of the Person object, because the scope of the name attribute is limited to the person object, that is, the outer layer is open to the inner layer, and the inner layer is closed to the external layer.

The closure concept is derived from this. The closure is a closed package that can deny access to the outer layer. The person object is a closure, and private variables in the package cannot be accessed outside the package, it can only be accessed through some special methods (privileged methods. Next, we will introduce the privileged methods.

3. Privileged Methods

The privileged method is equivalent to the get/set method that provides access and settings for private variables in the java class.

Function Person () {// underline the private property to indicate the private property var _ name; var _ age; this. getName = function () {return _ name;} this. getAge = function () {return _ age;} this. setName = function (name) {_ name = name;} this. setAge = function (age) {_ age = age;} var josh = new Person (); josh. setName ('Josh '); josh. setAge ('25'); console. log (josh. getName (); console. log (josh. getAge ());

At this point, the concepts of common attributes, private attributes, and closures have been fully discussed. This blog introduces the concept of closures in a very small space, but illustrates the most fundamental essence of closures, the context of the function does not have the right to access the variables defined in the function, so it forms a closure (a closed package ). With this concept, we will certainly be very useful when looking at the closure 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.