JavaScript Object-oriented programming and object access control examples

Source: Internet
Author: User

JavaScript is an object-based (object-based) language, and almost all of the things you encounter are objects. However, it is not a true object-oriented programming (OOP) language because its syntax has no class (class).

So what should we do if we're going to encapsulate the property and method (methods) into an object and even generate an instance object from a prototype object?

First, the original mode of the generated object

Suppose we look at a cat as an object, it has two attributes of "first name" and "Color".

The code is as follows Copy Code

var Cat = {

Name: ',

Color: "

}

Now, we need to generate two instance objects based on the specification (schema) of this prototype object.

The code is as follows Copy Code

var cat1 = {}; Create an empty object

Cat1.name = "hairy"; Assigning values to the properties of a prototype object

Cat1.color = "Yellow";

var cat2 = {};

Cat2.name = "Er mao";

Cat2.color = "BLACK";

OK, so this is the simplest package, which encapsulates two attributes in one object. However, there are two disadvantages to this writing, one is that if you generate more than a few instances, it is very troublesome to write, and the second is between the example and the prototype, there is no way to see what connection.

Object access Control Instance

The code is as follows Copy Code

function Cat (name, age) {
var name = name;
This.age = age| | 1;
This.setname = function (sname) {
THIS.name = sname;
}
This.getname = function () {
return this.name;
}
This.setage = function (nage) {
This.age = nage;
}
This.getage = function () {
return this.age;
}
}

Cat.prototype.say = function () {
Console.log (' I am ' +this.name+ ', I am ' +this.age ');
}

var kk = new Cat (' KK ');
Console.log (kk.name);//undefined @private
Kk.setname (' Deeka ');
Console.log (Kk.getname ()); Deeka
Kk.setage (2);
Console.log (Kk.getage ()); 2
Kk.age = 3;
Console.log (kk.age);//3 @public
Kk.say (); I am Deeka, I am 3

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.