Js construction and prototype)
1. Object-oriented: js prototype
Java has classes and instances. js only has Constructors (function Cat (name, age) {this. name = name; this. age = age}), in order to achieve data sharing and abstract common attributes, a prototype is added.
Eg:
Function Cat (name, age ){
This. name = name; // here this is equivalent to the instance in java
This. age = age;
This. work = function (){
Alert ("I am working ");
}
}
Var cat1 = new Cat ("cat1", 13 );
Var cat2 = new Cat ("cat2", 15 );
Both cat1 and cat2 have the work attribute, but the same attribute is obviously redundant, resulting in waste and can be abstracted out of the prototype.
Function Dog (name, age ){
This. name = name;
This. age = age;
}
Dog. prototype = {work: function () {alert ("I am working! ")} Or
Dog. prototype. work = function (){
Alert ("I am working ");
}
2. encapsulation:
Original mode: var cat ={}; cat. name = "cat1"; cat. id = "id1 ";
Original mode improvement: var cat = function cat (name, id) {return {name: name, id: id}, equivalent to calling a function
Constructor mode: function (name, id) {this. name = name; this. id = id}
The difference between adding new and not new during initialization of constructors in js
Function Dog (name, age ){
This. name = name;
This. age = age;
}
Dog. prototype = {work: function () {alert ("I am working! ")}}
Var dog1 = Dog ("dog1", 12); // This is equivalent to calling a common function. The prototype work is not generated and an error is returned when the work attribute is called.
Var dog2 = new Dog ("dog2", 13); // call the constructor to initialize the prototype work
Var dog3 = new Dog ("dog3", 14 );
Dog2.constructor = Dog; dog3.constructor = Dog
To solve the problem of generating instances from a prototype object, Javascript provides a Constructor mode.
The so-called "constructor" is actually a common function, but this variable is used internally. You can use the new operator to generate an instance for the constructor, and this variable is bound to the instance object.