Object-oriented is to add attributes to an object and complete the requirements through the properties of the object.
A simple example is to create an object and add properties to the object.
var obj = new Object ();
Obj.name = ' Tom ';
Obj.age = 18;
Obj.showname = function () {
return this.name;
};
Obj.showage = function () {
return this.age;
};
One package
In the function encapsulation, it becomes the Factory mode
function Person (name,age) {
Raw materials
var obj = new Object ();
Processing
Obj.name = name;
Obj.age = age;
Obj.showname = function () {
return this.name;
};
Obj.showage = function () {
return this.age;
};
Factory
return obj;
}
This encapsulation method is relatively simple, but the disadvantage is that every time a function is called, a new object is created, so the properties in the object are independent and there is no intrinsic connection between the instances.
Constructors and prototypes
function Person (name,age) {
THIS.name = name;
This.age = age;
}
Person.prototype.showName = function () {
return this.name;
};
Person.prototype.showAge = function () {
return this.age;
};
JavaScript specifies that each constructor has a prototype property that points to another object. All the properties and methods of this object are inherited by an instance of the constructor, so that the attributes on the prototype used by all the instances are in fact the same memory address, thus improving the efficiency of the operation and linking the instance to the prototype.
Two inheritance
1. Attributes in the inheritance constructor
function Animal () {
this.species = ' animals ';
}
function Dog (name,age) {
Animal.apply (this,arguments);
THIS.name = name;
This.age = age;
}
2, the method of inheriting the prototype
function Animal () {}
animal.prototype.species= ' animals ';
function Cat (name,age) {
THIS.name = name;
This.age = age;
};
A:
Cat.prototype = Animal.prototype;
Cat.prototype.constructor = Cat;
Cons: Polluting parent prototype objects
B:
Cat.prototype = new Animal ();
Cat.prototype.constructor = Cat;
Disadvantage: Takes a property in the parent constructor, consumes memory.
C:
for (var name in Animal.prototype) {
Cat.prototype[name] = Animal.prototype[name];
}
Cat.prototype.constructor = Cat;
Cons: Parent and child relationships are broken.
D:
var F = function () {};
F.prototype = Animal.prototype;
Cat.prototype = new F ();
Cat.prototype.constructor = Cat;
E:
Cat.prototype = Object.create (Animal.prototype);
Cat.prototype.constructor = Cat;
JavaScript Object-Oriented programming