Object-oriented is the idea of programming, JAVA, PHP, C#, C++,.net (dot net), JS… It’s all object oriented programming
Process oriented programming thought: C language is process oriented
HTML, CSS: markup languages are not programming languages. There is no such thing as object-oriented programming
Less, SASS: A CSS precompiled language designed to turn CSS into a programming language (object-oriented programming language)
object-oriented
JS itself is an object-oriented language, not an object-oriented language
JS can simulate the implementation of inheritance and encapsulation, but not the implementation of polymorphism, so we say that JS is an object-based language, rather than object-oriented language.
JavaScript implements object-oriented programming through prototype
Three main features of object orientation:
1, encapsulation
Hide the attributes and implementation details of objects, and only provide public access to the external, which isolates changes, facilitates use, and improves reusability and security.
2, inheritance,
Improve code reuse; Inheritance is a prerequisite for polymorphism.
3, polymorphism
A reference variable defined by a parent class or interface can point to an instance object of a subclass or concrete implementation class. Improve the extensibility of the program.
Polymorphism refers to the behavior of different subclass objects by passing them to the superclass object. Polymorphism provides better extensibility for programs, as well as code reuse. Because JS is a weakly typed language, polymorphism cannot be implemented
Object, class, instance
Object: In programming language object is the general term, everything is object (all we will study and use are objects)
Classes: Are abstract. Specific subdivision of an object (subdivided into categories by attributes or properties)
Example: Is concrete. A concrete thing in a class (object data type)
An instance is an object
[In real life]
+ people
+ Normal human
+ programmer class
I am an example of the programmer category
Built-in classes used in javascript (built-in classes are functions)
- Of data types:
Number
: Each number or NaN is an instance of itString
: string classBoolean
: BooleanNull
Undefined
The browser blocks us from manipulating the Null or Undefined classObject
: object class, of which each object data type is an instanceArray
: array classRegExp
: regular classDate
Date: class- .
Function
: function class, of which each function is an instance
- Of element objects and sets of elements
HTMLCollection
: Element collection classNodeList
: node collection classHTMLDivElement
: HTML div tag classHTMLElement
: HTML tag classElement
: the tag classNode
Node class:EventTarget
: Event object class
Each HTML tag has its own built-in class
// Get the element collection class
getElementsByClass
getElementsByTagName
querySelectorAll
Copy the code
// Get node set class method:
getElementsByName
childNodes
Copy the code
The current stage of learning the meaning of object-oriented for us
Explore arrays:
1. Create an instance of an array and explore its basic syntax and structure
2. If we want to study the functions and methods of data, we only need to look at the Array/Object class to give it what methods
The problem
Document.getelementbyid Its context can only be Document, why not others? (Console dir(document))?
Because getElementById is a method that only exists on the Document class, not on any other tag class; And document is an instance of Document, so document can use this method
When we encounter a data (object), we first consider whose instance it is, and what methods does the class provide to it
Create data values based on object orientation
//=> How literals are created
var arr=[12.23]
// Create an array in a strict object-oriented (constructor) manner
var ary=new Array(a);Copy the code
There is no difference at the core between the two methods of creating an instance of the Array class, but there is a difference in syntax
- 1. What does literal creation pass in, adding content to an array
- 2. How constructors are created
new Array(10)
; // Create an array of length 10 with each entry emptynew Array('10')
; ifOnly one argument is passed
andThe argument is not a number
, which is equivalent toTake the current value as
An array ofThe first term goes in
New Array (10, 30)
; / / ifPass multiple arguments
Instead of setting the length, store the passed content as each item in the array
var obj={name:'Hahaha'}
var obj=new Object(a)// It can only be used to create empty objects. If you need to add key/value pairs, you can add them one by one after the creation
Copy the code
var num=12; // A literal creates a primitive datatype value (but is also an instance of Number, which can call its method)
var num=new Number(a);// The constructor creates an instance of Number (or the method Number assigns to it), but the result is of the object data type
Copy the code
In serious object orientation, all classes have to create instancesIf the value is created in new mode, the result cannot contain the basic data type value, which is the object data type value
But the base data type value is an instance of the corresponding class and you can use the methods of the corresponding class
Constructor design pattern
In JS, when we use new XXX() to execute a function, the function is not a normal function, but a class, the result is called the current class instance (object data type this), we call this new XXX() implementation of the constructor design pattern
The use of constructors, mainly for the creation of classes and instances, that is, based on object-oriented programming ideas to achieve some requirements processing
function Fn(name,age,job){
this.name=name;
this.age=age;
this.job=job;
this.getName=function(){
alert(this.name)
}
}
//Fn(); // Normal function execution
var f=new Fn(); // The constructor performs Fn as a class
//f is an instance of the current class "constructor design pattern" (we usually capitalize the first letter of the class name)
/** 1, create object without display 2, assign attributes and methods to this object 3, return no statement **/
function Fn2(){
console.log(1)}var f=new Fn2();
//Fn2 will print 1 first, but f is an instance of Fn2 and an object, so f is an empty object because there is no this. XXX = XXX operation {}
Copy the code
Normal function execution VS constructor execution
Ordinary function execution
Create a new private scope
2. Copy the string that created the function into a real JS expression
Parameter assignment
4. Variable promotion
5. The code executes from top to bottom (the value after return is the result returned by the current function)
6. Stack memory is released or not released
function fn(num){
this.num=num; //=>this indicates that the window is equivalent to adding a num attribute to the global object. The attribute value is 10
var total=null;
total+=num;
return total;
}
var f=fn(10) //=>f:10
Copy the code
Constructor execution
- First, as with normal function execution, a new private scope needs to be opened
- 2. Copy the string that created the function into a real JS expression
- 3. Perform operations similar to normal functions in private scope: parameter assignment, variable promotion
- Constructors have special operations of their own before the code executes from top to bottom:
By default, the browser creates a value of the object data type in the current scope (opens up heap memory) and makes the execution body of the current function point to the created object.
- Execute the constructor code top-down like a normal function:
This. XXX=XXX these operations add the property name and value to the object created by default
- After executing code, even if there is no return in the function, in constructor mode:
By default, the browser returns the created object outside the function
(equivalent to the default return this;)
Constructor execution has both the usual function execution side and some operations of its own
During constructor execution, the object created by the browser by default (this in the function body) is an instance of the current class, and the browser returns the default instance, so we say: new Fn() executes, Fn is a class, and returns an instance of Fn
The constructor executes, and this in the constructor body is an instance of the current class (which is a JSON).
Instance is object Data Type (JSON)
function Fn(num){
In constructor mode, this appears in the method body as an instance of the current class (this.xxx =XXX adds attributes to the current instance)
this.num=num;
}
var f= new Fn(10)
console.log(f.num) / / 10
Copy the code
Understand the steps that constructors perform in depth
When a constructor, or a class, is executing without passing any arguments, it doesn’t matter whether or not we enclose the parentheses.
Constructor execution has both the normal function execution side and its own special side, but only its own special side is relevant to the instance (i.e. This.xxx =XXX is equivalent to adding attributes to the current instance).
This.XXX=XXX is the only private variable that has no direct relation to the instance
In constructors, variables declared using var and function are called private variables; The scope of a private variable is valid only within the constructor. That is, it can only be used inside a constructor. Outside the constructor, it cannot be called using either the object name or the class name
Each instance created by a class is a separate entity (a separate heap memory space), which is different and independent of each other. (Some developers in the market call this pattern a singleton pattern, which is wrong. In JS, this pattern is called the constructor design pattern.)
All properties assigned to the instance in the constructor body via this.XXX=XXX are for the current instancePrivate property
The constructor body (which returns an instance: object type value by default) has no effect on the last instance returned when we manually set a return value to a primitive type. However, if we return a value that references a data type, the default instance will be replaced by an instance
function Fn(){
var num=100;
this.name='hahah'
this.sum=function(){}}var f1=new Fn(); / / Fn; An instance of F1 Fn
var f2=new Fn; // The parentheses can be omitted if no argument is passed
// Private variables are independent of instances
console.log(f1.num) //undefined
console.log(f1.name) //hahah
// Different instances are different spatial addresses
console.log(f1===f2) //false
console.log(f1.sum===f2.sum) //false
Copy the code
function Fn(){
this.name='aaa'
return 10;
}
var f=new Fn();
console.log(f) //f:{name:'aaa'} f is still an instance of the current instance
function Fn(){
this.name='aaa'
return {name:'bbb'};
}
var f=new Fn();
console.log(f) //f:{name:' BBB '} f is not an instance of Fn, but a manually returned object
Copy the code
XX instanceof YY: tests whether the current instance XX belongs to a class YY
Instanceof: used to check whether the current instance XX belongs to a class YY
Instanceof addresses typeof’s inability to recognize whether it is an array or a regular
Test data types: typeof, instanceof, constructor, the object. The prototype. Tostring. Call
function Fn(){}var f=new Fn();
console.log(f instanceof Fn) //=>true
console.log([] instanceof Array) //=>true
console.log($/ / ^ instanceof Fn) //=>false
console.log(f instanceof Fn) //=>true
[] instanceof Object
true$/ / ^instanceof Object
true$/ / ^instanceof Array
false
[] instanceof Array
true$/ / ^instanceof RegExp
true
Copy the code
Implement Instanceof manually
Instanceof is used to determine whether an object is an instanceof another object (constructor). Instanceof looks up the prototype chain until null returns false if it is not an instanceof the later object, and true otherwise
function instanceofMy(obj, constructor) {
// the constructor must be a function
if (typeof constructor! = = 'function') throw new Error('instance error')
if (! obj || (typeofobj ! = ='object' && typeofobj ! = ='function')) return false// Get the prototype objectlet proto = constructor.prototype/ / ifobjThe prototype object is notnull
while (obj.__proto__) {
if (obj.__proto__ === proto) return true
obj = obj.__proto__
}
return false
}
console.log(instanceofMy(() = > {}, Function)) // true
Copy the code
hasOwnProperty VS in
Xx.hasownproperty (YY) : Checks whether the current property YY is a private property of XX.
YY in XX: used to check whether the current property YY belongs to the object XX (whether it is a private or public property of the object, if it returns true)
var obj={
name:'aaa'.age:18
}
'name' in obj //true
'sex' in obj //false
'toString' in obj //true (公有属性)
'hasOwnProperty' in obj //true (公有属性)
//hasOwnProperty is a property method provided in the Object built-in class, which can be used as long as the current Object is an instance of Object
obj.hasOwnProperty('name') //true
obj.hasOwnProperty('toString') //false
Copy the code
function Fn(){
this.num=100;
}
var f=new Fn();
f.hasOwnProperty('num') //true
Copy the code
Checks if a property is a public property of the current object
Is a property of an object
2. Not a private property of the object
function hasPubProperty(attr,obj){
return (attr in obj) && (obj.hasOwnProperty(attr)===false)
}
hasPubProperty(hasOwnProperty,{XXX:'XXX'})
Copy the code