Javascript object oriented
I’ve been talking about object-oriented, and I’ve been talking about Javascript being an object-oriented, procedural, functional programming language. So what exactly is object orientation?
Object Oriented Programming (OOP) is a computer Programming architecture. A basic principle of OOP is that a computer program is composed of a single unit or Object that can act as a subroutine. OOP achieves the three main goals of software engineering: reusability, flexibility, and extensibility, with the core concepts of classes and objects. Object-oriented programming – Baidu Encyclopedia
Now that we know what object orientation is, and that the core concepts of orientation are classes and objects, we come to the second question: what is a class? What is an object? Are classes related to objects?
The object that one studies is itself an object, such as a specific person, a tree, a dog, a rule, etc. Objects contain their own properties, methods, and combinations of implementation data and operations. By the way, when you were learning data structures, you saw this saying, data structures are data + operations
A class is an abstraction of objects with the same characteristics and behavior, such as Person, Tree, Dog, Rule, etc., that contains the form and operations of data
“Relationship between objects and classes” An instance of a class is an object, which can be understood as a class is a mold, and an object is a product created from a mold
With that said, let’s get right to the code
This is a Person class
// The abstraction of a person defines characteristics such as name, age, height, weight, etc., as well as behaviors such as speaking, running, etc
class Person {
name: string;
age: number;
height: number; weight: number; . talk(){ console.log('speak english'); } run(){} .} // Keven is an object, he is a concrete person, he contains the name, age, height... You can talk, you can run... const keven:Person = new Person(); Copy the code
Three characteristics of object orientation
- The “inheriting” subclass inherits its parent class and behaves much like its parent (inheriting its features and behaviors), although subclasses can also contain their own features and behaviors;
// YellowPerson inherits Person's features and behavior
// Although YellowPerson does not declare any properties and methods internally, it already has name, age, height...
class YellowPerson extends Person {
playTableTennis() {}
}
Copy the code
- A “polymorphic” subclass overrides a parent class, and subclasses that inherit from the same parent class behave differently for the same feature or behavior
// Subclasses inherit from the parent class, but subclasses behave differently for the same feature, such as Chinese and African
class YellowPerson extends Person {
talk() {
console.log('Speak Chinese');
}
} class BlackPerson extends Person { talk() { console.log('Speak Afrikaans'); } } Copy the code
- “encapsulation“Internal implementation details are hidden from the outside, and access to members is controlled using property descriptors, which are generally available
Private, protected, public
class Person {
private assets: number; // He has a lot of assets that he doesn't want anyone (including his family) to know about except himself
protected houseKey: string; // The man doesn't want outsiders to know the keys to his house, except his own family, such as his son
public name: string; // His name is available to everyone
}
Copy the code
Javascript” Object Oriented”
As mentioned above, Javascript can be object-oriented, and the core of object-oriented is class and object, so how do classes and objects represent in Javascript?
The object of the Javascript
Javascript data types are divided into: number, string, Boolean, NULL, undefined, symbol and object, where object is the Javascript object. Javascript is not all objects because of other data structures, that is, not everything is an object in Javascript
There are many Javascript objects, such as the following built-in objects: Object, Array, Function, RegExp… Of course, you can also create your own objects
const obj1 = {}; // This is an example
const obj2 = new Object(a);// construct call, use very little
const obj3 = new Person(); // Construct the call
const obj4 = Object.create(null); // Not much use
Copy the code
Javascript object properties, methods
Properties and methods
You can use “.” or “[]” to access properties and methods. We generally distinguish between the members of an object: those whose values are functions are called methods, and those whose values are non-functions are called attributes, as in other object-oriented languages.
In Javascript, however, a function does not belong to an object (it is just a reference), that is, it is not a method of an object, so the name method is not very strict. It only returns a function when accessing an object property.
“There are a few caveats“
- Difference between “.” and “[]” :
- “.” is generally called attribute access, and the attribute name must satisfy the naming convention; []” Commonly referred to as key access, key names can accept any UTF-8 / Unicode string
- “.” Attribute names can only be constants;” []” can be a variable
- “[]” can be used to evaluate attributes in ES6
- “.” and “[]” are not the same in AST,
. => PropertyAccessExpression; [] => ElementAccessExpression
[[GET]], [[PUT]]
Object to get properties and set properties. Note that [[GET]] and [[[PUT]] are operations on objects, unlike getters and setters, which are operations on certain properties of objects. Here one mouth, [[GET]] and [[PUT]] is the document ES5.1, ES6 document is within [[GET]] and [[SET]]
The following code pretends to simulate a [[GET]] and [[PUT]]. Note that [[GET]] and [[PUT]] do not focus only on the object, but also look up the prototype chain
const obj = {};
const proxy = new Proxy(obj, {
get() {}, // pretend to be [[GET]]
set() {}, // pretend to be [[PUT]]
}); Copy the code
[[GET]] and [[PUT]]. If you want to know all of them, like [[Delete]], please click here — Algorithms for Object Internal Methods
Attribute descriptor
The default property descriptor, Enumerable, and Writable, is false
- Public property descriptors:
Configurable, enumerable
{
configurable: false.// The property cannot be changed, cannot be deleted, cannot be reset, and fails to silence an action that cannot be performed. Ps in strict mode will report an error
enumerable: false.// The property cannot be traversed. Ps some methods are available, for example, Reflect the ownKeys (), Object. GetOwnPropertyNames/getOwnPropertySymbols ()
}
Copy the code
-
Mutually exclusive property descriptors. The following two sets of property descriptors are mutually exclusive
The get and set
: Intercepts properties for getting and setting
{
get() {}, set() {},}
Copy the code
Writable, the value
{
writable: false.// This property cannot be modified. If modified, silent error occurs. Ps in strict mode will report an error
value: xx,
}
Copy the code
Existence detection
The following methods are used to detect the existence of objects’ properties and methods:
Whether to test prototypes | Whether enumerable=false is included | Whether to include symbol | |
---|---|---|---|
in |
is | is | is |
Reflect.has |
is | is | is |
hasOwnProperty |
no | is | is |
The iteration
The following method iterates over an object
Whether to traverse the prototype | Enumerable = False | Whether to traverse symbol | |
---|---|---|---|
for... in |
is | no | no |
Object.keys() |
no | no | no |
getOwnPropertyNames |
no | is | no |
getOwnPropertySymbols |
no | is | is |
Reflect.ownKeys() |
no | is | is |
The prototype of the Javascript
Every Javascript object has a special property called [[Prototype]], which is the object’s Prototype. [[Prototype]] is essentially a reference to another object.
Available in some browsers__proto__
Access the property, such as Google, but by standard, use itObject.getPrototypeOf()
To obtain
Each object has a special attribute [[Prototype]], [[Prototype]] that points to another object, and the other object has a [[Prototype]] attribute… Until null terminates, the prototype link made up of this object is the prototype chain
If [[Prototype]] does not exist and the object’s [[Prototype]] is not null, the Prototype chain lookup will continue along the object referenced by [[Prototype]] until the attribute or object is null is found
Prototype differs from [[prototype]]
The function also has a prototype property, and when the new constructor is called, the generated object has access to Prototype. Since they are both called prototypes, we distinguish them here:
“Prototype” is used in constructors, and the mock class “[[prototype]]” is used in objects for instances. [[prototype]] [[prototype]]
function Person {}
Person.prototype.xx = xx;
// person points to Person.prototype with [[Prototype]], thus accessing the Prototype object
var person = new Person();
Copy the code
Javascript “classes”
Before ES6, Javascript had no concept of classes, and objects were generated by “new constructors calling constructors”. After ES6, classes are available, so does that mean Javascript will have classes after ES6?
The difference between Javascript “classes” and other language classes
It is important to clarify the concept that “Javascript has no classes” and that classes in Javascript are merely mock classes (compile with typescript or Babel and see the compiled code).
/ / typescript3.9
class Person {
private name: string = ' ';
talk(): void {}
}
Copy the code
The compiled
// javascript
var Person = /** @class */ (function () {
function Person() {
this.name = ' ';
}
Person.prototype.talk = function () {}; return Person; }) ();Copy the code
Another way to think about it is that Javascript uses syntactic sugar all the time to pretend that it has classes when it doesn’t. This will be illustrated in several ways
instantiation
In object oriented, a class is a mold, and the step of generating something from a mold is called instantiation, such as new Person(). When Javascript generates objects, it relies on construction calls rather than class instantiations, such as new Person(). [[Prototype]] is a reference to Prototype, so objects and classes can interact with each other
/ / CPP class
class Person {
public:
int age;
// constructor Person(int _age) { this->age = _age; } }; Person *p = new Person(22); Copy the code
/ / js "class"
// constructor
function Person(age) {
this.age = age;
} Person.prototype.getAge = function () { return this.age; }; Person.prototype.ind = [1.2.3]; var p = new Person(22); // new is the construction call p.ind.push(4); var p2 = new Person(23); p2.ind; // [1, 2, 3, 4], objects affect each other Copy the code
“Simple implementation of Javascript new“
- Create a new object, newObj
- NewObj assignment [[Prototype]]
- Run the constructor and use call, apply to specify this as newObj
- The constructor returns a value after it is run, if it is an object, otherwise newObj is returned
function newSelf(construct, ... args) {
var newObj = Object.create(construct.prototype); Assignment / / [[Prototype]]
Var newObj = object.setProtoTypeof ({}, construct. Prototype);
varresult = construct.call(newObj, ... args);// The constructor runs
return typeof result === 'object'&& result ! = =null ? result : newObj; } Copy the code
inheritance
When a Javascript” class “inherits, a subclass does not inherit the properties and methods of its parent class. Instead, it relies on [[Prototype]] to access the Prototype of its parent class
// CPP class inheritance
class YellowPerson : public Person {
public:
YellowPerson(int _age) : Person(_age) { this->age = _age; }
};
YellowPerson *yp = new YellowPerson(22); Copy the code
function YellowPerson(age) {
Person.call(this, age); // Constructor inheritance
}
// Prototype inheritance
YellowPerson.prototype = new Person(); YellowPerson.prototype.constructor = YellowPerson; var yp = new YellowPerson(22); Copy the code
polymorphism
“Javascript” classes will not follow the [[Prototype]] feature to implement polymorphism if the property is found by [[GET]]
Javascript” delegate oriented”
“Delegate oriented” : Some objects delegate the request to another object, Javascript you Don’t Know, when they can’t find attributes and methods themselves.
var person = {
showAge() {
return this.age;
},
};
var yellowMan = Object.create(Person); yellowMan.age = 22; // yellowMan does not contain the age attribute itself, but relies on [[Prototype]] to access the age attribute of person Copy the code
Personally, delegation-oriented Javascript works just as well as object-oriented, with the following minor differences:
- In object oriented: Use the parent class (Person) to store attributes and methods, then reusepolymorphismTo implement different operations
- In delegation-oriented: It is best to keep state on the principal (YellowPerson) rather than the delegate object (Person)
Javascript inheritance
/ / parent class
function Person(name) {
this.name = name;
this.ind = [1.2.3];
}
Person.prototype.getName = function () { return this.name; }; Copy the code
Constructor inheritance
function YellowPerson(name) {
Person.call(this, name);
}
Copy the code
“Advantages” :
- Attributes not shared between subclasses, “not shared even for reference data types”
- Constructors can pass arguments
Weaknesses:
- Cannot get methods and properties defined on the prototype of the parent class
Prototype chain inheritance
function YellowPerson() {}
YellowPerson.prototype = new Person();
YellowPerson.prototype.constructor = YellowPerson;
Copy the code
“Yellowperson. prototype” = person. prototype. This will cause the prototype of the subclass to point to the same object as the prototype of the parent class. All other classes (the parent class and other subclasses that inherit from the parent class) change
“advantages“
- Gets methods and properties defined on the prototype of the parent class
“disadvantages“
- The constructor cannot take arguments
- Subclasses can access the attributes of their parent class, but they share the attributes of their parent class, which is fine if they are primitive types, and affect each other if they reference types
- The constructor property needs to be fixed
Combination of inheritance
function YellowPerson(name) {
Person.call(this, name);
}
YellowPerson.prototype = new Person();
YellowPerson.prototype.constructor = YellowPerson;
Copy the code
“advantages“
- Gets methods and properties defined on the prototype of the parent class
- Subclass attributes not shared, “not shared even for reference data types”
- Constructors can pass arguments
“disadvantages“
- The parent class runs twice with more instances of the parent class
- The constructor property needs to be fixed
Parasitic combinatorial inheritance
function YellowPerson(name) {
Person.call(this, name);
}
YellowPerson.prototype = Object.create(Person.prototype); // Object.setPrototypeof also works
YellowPerson.prototype.constructor = YellowPerson;
Copy the code
“advantages“
- Gets methods and properties defined on the prototype of the parent class
- Subclass attributes not shared, “not shared even for reference data types”
- Constructors can pass arguments
- The parent class runs only once, with no redundant instances
“disadvantages“
- The constructor property needs to be fixed
This article is formatted using MDNICE