preface

Record that front-end object-oriented learning is complete

  • 1. Object oriented
  • 2. Several ways to create objects with JS
  • 3. Several ways to implement JS inheritance
  • 4.JS to achieve deep cloning
  • 5.Several cases that this refers to

1. Object oriented

Three characteristics of Object Orientation (encapsulation, inheritance, polymorphism)

1. The encapsulation

Definition: Create an object that holds the properties and functions of an object in the real world. Scattered data is encapsulated into the object structure to facilitate the management and maintenance of large amounts of data.

A. The first way to encapsulate objects – direct quantities

Var obj={// new Object() a: 1, b: 2 fn: function(){console.log(this.a)}}Copy the code

B. The second way to encapsulate an Object – new Object()

var obj= new Object();
obj.a = 1;
obj.fn = function(){ 
    console.log(this.a)
}
Copy the code

The access method of obj. A reveals the core principle of JS language: all objects in JS are associative arrays

    1. Storage structure: all combinations of key-value pairs \
    1. When accessing a member:
    • Object name/array name [” member name “]
    • The abbreviations are: object name/array name. Member names, such as obj[” a “] and obj.a
    1. Forcing a value to a location that does not exist not only gives no error, but also automatically adds the property. So adding a new property or method to an object can be done by force assignment. \
    1. Forcible access to a value that does not exist does not return an error but returns undefined
    1. You can iterate through them with a for in loop

C. The third way to encapsulate objects – constructors

function Obj(a) { this.a = a; this.b = b; This.fn = function(){console.log(this.b)}} var obja = new Obj(1) // Use constructors to create multiple objects repeatedlyCopy the code

New does four things

  • 1. Create a new empty object
  • 2. Make the child object inherit the constructor’s prototype object (see inheritance below)
  • 3. Call the constructor
    • Creates a new object in the constructor this -> new
    • Add specified properties and methods to a new object by forcing an assignment inside the constructor
  • 4. Return the address of the new object in the variable to the left of =

To sum up, this refers to two cases:

  • Obj. Fun () this->. Obj object in fun
  • New Fun() This ->new creates a new object in Fun

2. The inheritance

Throw problems: method definitions are placed in constructors, function is executed each time new, creating multiple copies of the same function over and over again! Waste of memory solution: so many children object to use the same function and attribute values, can use inheritance to solve the definition: the parent object member, child object without repeated creation, can be directly used! Just like using your own members! This. Property name/method name ()

Inheritance in JS is implemented through prototype objects (prototype objects: parent objects that hold common property values and methods in all child objects)

Each constructor has a prototype attribute that points to its matched prototype object. • The second step of new automatically makes the newly created child object inherit from the constructor’s prototype object. • The second step of new automatically sets the __proto___ property of the child object, pointing to the constructor’s prototype object.

Function Obj(a) {this.a = a; this.b = b; This.fn = function(){console.log(this.b)}} Obj. Prototype. fn = function(){this.fn = function(){this.log (this.b)}} Obj Obja = new Obj(1) obja.__proto__ == Obj. Prototype // true Specifies the prototype of the parent objectCopy the code

This in the prototype object

  • Judge this by where and how it is called! Don’t look where is the definition
  • Because the common methods in the prototype object will use child objects. Method name () “is called.
  • The child object in the prototype object before the **.(dot)** that will call this public function.
  • Simply remember: who calls refers to who
function Student(name,age){
    this.name = name;
    this.age = age;
}
Student.prototype.intro = function(){
    console.log(this.name, this.age)
}
var zs = new Student('zs', 18)
var ls = new Student('ls', 19)
zs.intro() // ('zs', 18)
ls.intro() // ('ls', 19)
Copy the code

This refers to the third type: a child object before the.(point) of a common method called by this-> in the future

It is also possible to extend the prototype chain: a chain structure formed by hierarchically inheriting multiple levels of parent objects. This refers to several cases in this article

3. The polymorphism

Definition: The same function has different states in different situations

  • A. Overload: Same function, input different parameters, execute different logic
  • A. overwrite B. overwrite

Members inherited from the parent object are unusable and are overridden in child objects with the same name

var ww = new Student('ww',20)
ww.intro = function () {
    console.log('overwrite', this.name, this.age)
}
ww.intro() // (overwrite, ww, 19)
Copy the code

2. Summary of 10 ways to create object with JS

There are three

Var obj = {}

2. new Object()

Function Obj(){}

4. Factory function mode

Function createObj(name,age){var obj = new Object() obj.name = name; obj.age = age; obj.intro = function(){ console.log(this.name,this.age) } return obj; } console.log('obj: ', createObj('ty',18));Copy the code

5. Primitive object mode

Prototype function Obj() {} Obj. Prototype. name = 'ty'; Obj.prototype.age = 18; Obj.prototype.intro = function () { console.log(this.name, this.age) }; var o1 = new Obj(); Name console.log('o1: ', o1); var o2 = new Obj(); O2. name = 'wd' // same as console.log('o2: ', o2);Copy the code

6. Hybrid mode (constructor + prototype object)

Function Obj(name, age) {this.name = name; function Obj(name, age) {this.name = name; this.age = age; } Obj.prototype.intro = function () { console.log(this.name, this.age) }; var o1 = new Obj('ty', 18); console.log(o1);Copy the code

7. Dynamic mixing

// Create the exact same object and add personalization attributes to the child objects. // Disadvantages: For point 6, the dynamic mixing of transformations is encapsulated but semantically inconsistent. In fact, if only makes sense when creating the first object. function Obj(name, age) { this.name = name; this.age = age; if (Obj.prototype.intro === undefined) { Obj.prototype.intro = function () { console.log(this.name, this.age) }; } } var o1 = new Obj('ty', 18); o1.intro();Copy the code

Parasitic constructors

Function Obj(name, age){} function Obj2(name, age, height) {var o = new Obj(name, age); o.height = height; return o } var o1 = new Obj('ty', 18, 180); console.log('o1: ', o1);Copy the code

9. Safe constructors: closures

// Advantages: no this, no new! Function Obj(name, age) {var o = {getName: function () {return name}, setName: function Obj(name, age) {var o = {getName: function () {return name}, setName: function (val) { name = val }, getAge: function () { return age } } return o } var o1 = new Obj('ty', 18); console.log('o1: ', o1);Copy the code

Simply judge closure formation

10. ES6 Class

Front-end Interview Basics – Section 7 of ES6 Class

3. 7 ways to implement JS inheritance

Function Fruit(name) {// Define a parent constructor this.name = name; This. Intro = function () {console.log(this.name)}} Fruit.prototype console.log(this.name + ' is ' + color) }Copy the code

1. Prototype chain inheritance

// Take the instance of the parent class as the prototype of the subclass, Function Apple(name){} apple. prototype = new Fruit() apple.prototype. name = 'Apple '; Var apple = new apple () var apple = new apple ()Copy the code

Constructor inheritance

function Apple(name, color) { Fruit.call(this, Color = color} var apple = new apple ('apple', 'red')Copy the code

3. Instance inheritance

function Apple(name, color) { var o = new Fruit(name); // create a subtype instance. Color = color return o; } var apple = new Apple('apple', 'red')Copy the code

4. Copy inheritance

Function Apple(name, color) {var o = new Fruit(name); Prototype (const k in o) {Apple. Prototype [k] = o[k]} this.color = color} var () {Apple. Prototype [k] = o[k] apple = new Apple('apple', 'red')Copy the code

5. Combinatorial inheritance

function Apple(name, color) {
    Fruit.call(this, name)
    this.color = color
}
Apple.prototype = new Fruit();
Apple.prototype.constructor  = Apple
var apple = new Apple('apple', 'red')
Copy the code

6. Parasitic combination inheritance

function Apple(name, color) { Fruit.call(this, Name) this.color = color} (function () {var AppleNew = function () {} // Create an empty constructor AppleNew Fruit.prototype; Apple.prototype = new AppleNew()})(); var apple = new Apple('apple', 'red')Copy the code

7. ES6 Class inheritance

Front-end Interview Basics – Section 7 of ES6 Class

4.JS to achieve deep cloning

First implement the shallow clone step:

    1. Create an empty object
    1. Iterate over all properties in the object
    1. Each time a property is traversed, a new property is added to the new object with the same name and value
    1. Returns the processed object
var obj = { a: 1, b: 2, c: 3 }
console.log('obj: ', obj);
function shallowClone(obj) {
    var newObj = {}
    for (const key in obj) {
        newObj[key] = obj[key]
    }
    return newObj
}
var newObj = shallowClone(obj)
console.log('newObj: ', newObj);
Copy the code

Shallow clone: Copies only the first-level property value of an object. If the object also contains a reference type in its first level attribute, only the address is copied. If the object to be cloned contains an attribute value of the reference type, the cloned object shares the same attribute value of the reference type. If either party modifies the content of the reference type, the other party is affected. Therefore, it is necessary to carry out deep cloning: clone the attribute values of the reference type together, so that both the old and the new have their own reference type, and then it does not matter which party changes

There are three ways to implement procloning:

  • 1.JSON.stringify() + JSON.parse()
Parse (strObj) var strObj = {a: 1, b: 2, c: 3} var strObj = json.stringify (obj) var newObj = json.parse (strObjCopy the code

Disadvantages: Unable to clone undefined values and embedded functions

    1. Object.assign(target, source)
Var obj = {a: 1, b: 2, c: 3} var newObj = object. assign({}, obj) // Copy a new ObjectCopy the code

Disadvantages: This method is deep copy when the object has only primary attributes and no secondary attributes. But when there is an object in the object, this method, after the secondary property, is a shallow copy.

    1. Custom recursive cloning
var obj = { a: 1, b: 2, c: 3} function deepClone(obj) {var newObj = {} Typeof obj === 'object') {if (obj === null) {newObj = null; typeof obj === 'object') {newObj = null; } else if (array.isarray (obj)) {// newObj = []; Newobj. push(deepClone(obj[key]))}} else if (obj.constructor === RegExp) {// NewObj = obj} else {// Ordinary object, NewObj = {} for (const key in obj) {newObj[key] = deepClone(obj[key])}}} else {newObj = obj; } return newObj; } console.log(deepClone(obj))Copy the code

The last

Above way to summarize their learning summary, there are other ways a, welcome each big comment on Tony welcome each big god more correct, not praise, for supervision and correct ( ̄.  ̄) about the article is often asked about the interview can help you stay, the younger brother can complement to perfect the exchange of learning together, thank you for your bosses (~  ̄ del  ̄) ~