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 |