javascript object
Creating Object Method
1. Use constructors to create:
var cat = new Object();
cat.name = "hello kitty";
cat.age = 3;
cat.call=function(){
alert("miao~~");
}
2. Create an object using object literals
var cat {
name: "hello kitty",
age = 3,
call:function(){
alert("miao~~");
}
}
Because classes cannot be created in ECMAScript, although individual objects can be created by Object functions or object literals, creating many objects with the same interface can generate a lot of code.
-> Factory Model
3. Create objects through factory pattern
The concrete process of creating objects is abstracted, and the details of creating objects with specific interfaces are encapsulated by functions.
funtion createPerson(name , age , job) {
var o = new Object();
o.name=name;
o.age=age;
o.job=job;
o.sayname=funtion(){
alert(this.name);
}
return o;
}
var person1 = createPerson("zhangsan",12,"Student");
var person2 = createPerson("Lisi",44,"Teacher");
Factory pattern does not solve the problem of object recognition - > constructor pattern
4. Create objects through constructor patterns
(Supplement: Object impersonation)
function Person(name, age, job) {
this.name = name;
this.age = age;
this.job = job;
this.sayName = function() {
alert(this.name);
}
}
//1. The constructor does not have a new Object, but the background automatically var obj = new Object
//2.this is equivalent to obj
//3. The constructor does not need to return an object reference. It is automatically returned in the background.
var person1 = new Person("Xusan", 12, "Student");
var person2 = new Person("Lisi", 44, "Teacher");
//object masquerading
var o = new Object();
Person.call(o,'Micy',34,"Doctor");
alert(o.name);//o Get all of Person's
function Box(){}
var box = new Box();
//The problem of object recognition has been solved.
alert(person1 instanceof Person);//true
alert(person2 instanceof Person);//true
alert(box instanceof Person);//false
alert(box instanceof Box);//true
alert(person1.sayName()==person2.sayName());//The values of the methods in the true constructor body are equal
alert(person1.sayName==person2.sayName);//The citation addresses of the methods in the false constructor body are not equal (if they are the same, they can be global)
The constructor is also a function, with the first letter capitalized.
New instances of Person objects must be created using the "new" operator (unless the new operator is passed, it will be the same as a normal function)
Creating a Function (sayName) in the constructor pattern way results in different scoping chains and identifier parsing, each of which points to different method instances. However, creating multiple functional instances to accomplish the same task is of little significance. Transferring the definition of a Function to the outside of the constructor (equal to setting it as a global Function), but it can only be invoked by an object, whose global scope is somewhat inaccurate, and if the object needs to define more than one method, it is not encapsulated in the global - > prototype mode.
5. Creating Objects through Prototype Patterns
Creating each function has a prototype attribute (default, automatically generated), which is an object that contains properties and methods that can be shared by all instances of a particular type. Prototype is a self-contained property of a function. You can think of it as the object that the constructor created when instantiating.
Benefits: Let all object instances share the attributes and methods it contains, instead of defining object information in the constructor, add it directly to the prototype
function Box(){}//There is nothing in the current constructor, if any, called the instance attribute, the instance method.
//Prototype attributes, prototype methods:
Box.prototype.name="Lee";
Box.prototype.age=33;
Box.prototype.run=function(){
return this.name+" "+this.age+" running";
}
var box1 = new Box();
alert(box1.name);
alert(box1.run());
//If it is an instance method, different instantiations have different method addresses and unique
//If it is a prototype method, its address is shared
var box2 = new Box();
alert(box1.run==box2.run);//true
alert(box1.prototype);//undefined is an attribute of a function that cannot be accessed by an object instance
alert(box1.__proto__);//[object] A pointer to a prototype object
alert(box1.constructor);//FunctionBox (){} retrieves the constructor itself
//isPrototypeOf()
var obj = new Object();
alert(Box.prototype.isPrototypeOf(box1)); //true
alert(Object.prototype.isPrototypeOf(box1)); //true
//Instance attributes and methods are not shared, prototype attributes and methods are shared
box1.name="Milk";
alert(box1.name);//milk
alert(box2.name);//Lee
//Determine whether the specified attribute hasOwnProperty() exists in the instance
alert(box1.hasOwnProperty("name"));//true
alert(box2.hasOwnProperty("name"));//false
//Determine whether the specified attribute in operator exists in the prototype and instance
alert('name' in box2); //true
//Determining whether a specified attribute exists in a prototype: Combining the above two methods
delete box1.name;//Delete attributes in instances
delete Box.prototype.name;//Delete attributes in prototypes
//The execution flow of the prototype pattern: (if function Box () {name= "Jack"}, box 1. name prints Jack)
//1. Find the attributes or methods in the constructor instance first, and if so, return immediately.
//2. If there is no constructor instance, go to its prototype object and return if there is one.
Constructor mode:
Prototype mode:
(Interpretation: In the prototype schema declaration, there are two more attributes (_proto_ and constructor). These two attributes are automatically generated when an object is created. Proto attributes
An instance is a pointer to a prototype object, which can point to the prototype attribute constructor of the constructor. Constructor is an attribute of prototype. It can get constructor, which can be positioned by prototype pointer, and then get constructor itself, which can connect object instances and corresponding prototype objects.
Create prototype objects literally:
function Box(){}
Box.prototype = { //{} is equivalent to creating object new Object()
name:'Lee',
age:100,
run:function(){
return this.name+" "+this.age+" running";
}
}
var box = new Box();
alert(box.constructor); //function Object(){[native code]}
Creating objects with literal quantities and using constructors to create prototype objects are basically the same in use. But literal quantities are created in a constructor that does not point to the constructor of the instance object, but to Object, whereas constructors create prototype objects in the opposite way.
The literal constructor can be directed to the constructor of the instance object by mandatory pointing
Plus: The declarations of prototypes are sequential, and the rewritten prototype will cut off the previous prototype.
function Box(){}
Box.prototype = {
constructor:Box,
name:'Lee',
age:100,
run:function(){
return this.name+" "+this.age+" running";
}
}
//var box = new Box();
//alert(box.constructor); //function Box(){[native code]}
Box.prototype = {
age:200 //Cut off the relationship between the original prototype object and the constructor object instance
};
var box = new Box();
alert(box.run);//box.run is not a function
Prototype of native object:
var box = [5,6,234,3,7,8,9];
alert(box.sort());
//Is sort a method in the Array prototype object?
alert(Array,prototype.sort); //function sort(){[native code]}
//Functional Extension of Built-in Reference Types
String.prototype.addString=function(){
return this+" is adding ...";
}
alert('Lee'.addString());//Lee is adding ...
The drawbacks of prototype pattern creation objects are:
The initialization process of constructor parameters is omitted, and the initial values are consistent. Its biggest disadvantage is its greatest advantage, that is, sharing.
In order to solve the problem of constructing parameters and sharing, we can combine constructor + prototype pattern:
function Box(name,age){ //Use constructors that are not shared
this.name=name;
this.age=age;
this.family=['Dad','Mon','Sister'];
}
Box.prototype = {
constructor:Box,
run:function(){
return this.name+" "+this.age+" "+this.family+" running..."
}
}
var box1=new Box('Lee',100);
var box2 = new Box('Jack',200);
alert(box1.run());//Lee 100 Dad,Mon,Sister running...
alert(box2.run());//Jack 200 Dad,Mon,Sister running...
Prototype pattern: Whether or not the prototype sharing method is invoked, it initializes the prototype method, and when an object is declared, the constructor + prototype is not well encapsulated.
The Dynamic Prototype Model
6. Creating Objects through Dynamic Prototype Patterns
function Box(name,age){ //Use constructors that are not shared
this.name=name;
this.age=age;
this.family=['Dad','Mon','Sister'];
if(typeof this.run != "function"){//Avoid prototype initialization multiple times
Box.prototype.run = function(){
return this.name+" "+this.age+" "+this.family+" running..."
}
}
}
var box1=new Box('Lee',100);
var box2 = new Box('Jack',200);
Note: You can't rewrite prototypes by literal quantities anymore, which will cut off the connection between instances and new prototypes.
7. Create objects through the parasitic constructor pattern
Parasitic constructor pattern = factory pattern + constructor pattern
function Box(name,age){
var obj = new Object();
obj.name=name;
obj.age=age;
obj.run=function(){
return this.name+" "+this.age+" running...";
}
return obj;
}
var box1 = new Box("Lee",32);
alert(box1.run());
8. Create objects through a secure constructor pattern
The robust constructor pattern is similar to the parasitic constructor pattern, and it is suitable for some security environments. (Security environment: prohibit using this and new, this means prohibiting using this in constructors, and new means calling constructors without using the new operator)
function Box(name,age){
var obj = new Object();
obj.name=name;
obj.age=age;
obj.run=function(){
return this.name+" "+this.age+" running...";
}
return obj;
}
var box1 = Box("Lee",32);
alert(box1.run());
inherit
ECMAScript only supports inheritance and does not support interface implementation.
All objects inherit from Object
1. Inheritance is realized through prototype chain
function Box(){ //Inherited functions are called supertypes (parent class, base class)
this.name ='Lee';
}
function Desk(){ //Inherited functions are called subtypes (subclasses, derived classes)
this.age=100;
}
function Table(){
this.level = 'AAAAA';
}
//Inheritance through prototype chains: Assigning supertype instantiated object instances to prototype attributes of subtypes
//new Box() will give Desk both the information in the Box constructor and the information in the prototype.
//The prototype of Dest will get the information in Box's construction + prototype.
Desk.prototype = new Box();
Table.prototype = new Desk();
var desk = new Desk();
alert(desk.name);
var table = new Table ();
alert(table.name+" "+table.age);
//Supplement: Execution process Ibid.
Box.prototype.name='Jack';
alert(desk.name);//Lee
//A subtype is subordinate to itself or its supertype
alert(desk instanceof Object);//true
alert(table instanceof Box);//true
alert(desk instanceof Table);//false
Prototype chain inheritance flow chart:
2. Borrowing constructors (object impersonation):
In order to solve the problem that reference sharing and superclasses cannot be passed on, a technique called borrowed constructor, or object impersonation (forged object, classical inheritance), can be adopted.
//Using objects to impersonate inheritance
function Box(name,age){
this.name=name;
this.age=age;
}
Box.prototype.family='family';
function Desk(name,age){
Box.call(this,name,age);//object masquerading
}
var desk = new Desk('Lee',100);
alert(desk.name);//Lee
alert(desk.family);//undefined objects impersonate information that can only be inherited from constructs
3. Combinatorial Inheritance
By Prototype Chain + Borrowing Constructor
Solution to Parametric+Method Sharing
//Object impersonation + prototype chain
function Box(age) {
this.name = 'Lee';
this.age = age;
}
Box.prototype.run = function(){
return this.name + " " + this.age + " running..."
};
function Desk(age) {
Box.call(this, age); //Object impersonation, second call to Box
}
Desk.prototype = new Box(); //Prototype chain inheritance, first call to Box
var desk = new Desk( 100);
alert(desk.run());
4. Prototype Inheritance
Create new objects with prototypes and based on existing objects without creating custom types
//Temporary Transition Function
function obj(o) { //o is the object to be passed in
function F() {} //The F construct is a temporary new object used to store the passed object
F.prototype = o; //Assigning o-object instances to prototype objects constructed by F is actually equivalent to prototype chain inheritance.
return new F(); //Returns an instance of the object passed in.
}
//Literally create objects
var box = {
name: 'Lee',
age: 100,
family: ['Dad', 'Mom', 'Sister']
};
var box1 = obj(box);
alert(box1.family);//Dad.Mom,Sister
box1.family.push('Brother');
alert(box1.family);//Dad.Mom,Sister,Brother
var box2 = obj(box);
alert(box2.family);//Dad.Mom,Sister,Brother, shared
5. Parasitic inheritance:
= Prototype + Factory Model
Solves the problem of two calls to constructors in combination inheritance
//Temporary Transition Function
function obj(o) {
function F() {}
F.prototype = o;
return new F();
}
//Parasitic function
function create(o){
var f = obj(o);
//You can extend f
f.run = function(){
return this.name+"Method";
}
return f;
}
var box = {
name: 'Lee',
age: 100,
family: ['Dad', 'Mom', 'Sister']
};
var box1 = create(box);
alert(box1.name);
alert(box1.run());
6. Parasitic combination inheritance
//Temporary Transition Function
function obj(o) {
function F() {}
F.prototype = o;
return new F();
}
//Parasitic function
function create(box,desk){
var f = obj(box.prototype);
f.construtor=desk;
desk.prototype=f;
}
function Box(name,age){
this.name=name;
this.age=age;
}
Box.prototype.run=function(){
return this.name + " " + this.age + " running..."
}
function Desk(name,age){
Box.call(this,name,age);
}
//Through parasitic combinatorial inheritance
create(Box,Desk);//Replace Desk.prototype=new Box();
var desk = new Desk('Lee',100);
alert(desk.run());