js object-oriented summary

Class and Object Concepts

1) Object-oriented?

 Object-oriented is a kind of programming idea, which has two very important concepts: class and object.

Class: It is abstract, not specific, and a category is a class of things with the same characteristics. There are many classes in JS, and we can also define classes ourselves.

Object: Objects are created through classes, which are concrete. There are also many objects in JS, and we can also create objects ourselves.

2) Object?

There are many static features in an object, which are usually described by variables, and variables are also called attributes at this time.

There are many dynamic features in an object, which are usually described by functions, which are also called methods (attributes).

 An object is an unordered collection of properties (a collection of operations (CRUD)).

3) class?

Many classes are provided in JS, such as Number, String, Boolean, Object, Math, Date, ....

Create an object through a class, using the new operator to create, such as: let d = new Date();

 A new class can create an object.

4) Three laws, two chains:

Law 1: Everything is an object (arrays, functions, objects, and basic data types are also objects in certain situations)

Law 2: All objects are created through classes (functions are also classes in some cases)

Law 3: Objects are unordered collections of attributes (operations (CRUD) collections)

 Two chains: the scope chain and the prototype chain.

5) The object is an unordered collection of attributes (addition, deletion, modification and query in the object):

----Two ways to create objects: literal, new

let wc = {

name:"wangcai",

age:100,

say:function(){

console.log("wangwang...")}}

----- Access the properties in the object : through the dot operator, through the [""] syntax to access the properties in the object

! Please note a special case: if the property name is a variable: there is only one way to get the property in the object: [] Note that there are no quotation marks inside

! Add attributes to an object : through the dot operator, access the attributes in the object through the [""] syntax. Note that if an attribute with the same name is added, the attribute with the same name will be overwritten

! Set the properties of the object (refined settings): configuration: whether to delete; writable: whether the property value can be modified; enumerable: whether it can be enumerated; value: indicates the property value, no property value is given, the default value is: undefined; note, If there is no such property in the object, the fine-tuning belongs to adding this new property.

! remove property from object

delect object name. attribute name (delete a certain attribute in the object); by default, the attribute in the object can be modified, enumeration: use for in to traverse the attribute

Special example to delete attributes: a and b are global variables, and global variables are used as window attributes

var a = 110;

b = 666;

delete a; // Delete the a attribute on the window object

delete b; // Delete the b attribute on the window object

console.log(a) // 110 a has not been deleted

console.log(b) // ReferenceError: b is not defined b was deleted

Note: Global variables with var cannot be deleted, and global variables without var can be deleted

Note: If var is used, it is equivalent to setting configurable: false for the a attribute of the window object

! properties in an enumeration object

Take an example of properties in an enumeration object: for . . in

for(item in wc){

      console.log(item)

}

Give an example of enumerating properties in an object Object.keys(object name): Traverse the properties of the object, you can’t find the value, you can only find it inside yourself, and you can’t traverse non-enumerable properties

console.log(Object.keys(wc)) //  ["name", "age", "say"]

value: It can be directly modified or obtained.

Popularize a little knowledge: arrays can be understood as key-value pairs:

let arr = ["a","b","c"]

{0:"a",1:"b",2:"c"}

for(var i=0; i<arr.length; i++){

 console.log(arr[i]) }

Next, let’s talk about how to fine-tune the properties of an object:

1) Object.defineproperty(ObjectName, "PropertyName", {configuration table})

2) Object.defineproperty will directly define a new property on an object, or modify an existing property of an object, and return this object.

3) Object is a class class. xxx indicates that xxx is an attribute (static attribute) on the class

4) defineproperty is a static property on the Object class define means definition Property

! ! Note that the attribute name must be quoted when setting, otherwise an error will be reported. It will treat you as a variable, and variables cannot be refined to set characteristics.

! ! Pay attention to the characteristics of modifying attributes: once the setting cannot be deleted, then it can no longer be set and can be deleted! !

Let's take a standard example:

let wc = {

name:"wangcai",

age:100,

say:function(){

console.log("wangwang...")}}

Refined settings

Object.defineProperty(wc,"score",{

configurable: false, // The score attribute on the wc object cannot be deleted

value:100

});

delete wc.score

console.log(wc.score)

For example, define a constant that cannot be modified or deleted.

let obj = {};

Object.defineProperty(obj,"PI",{

writable: false, // cannot be modified

configurable: false, // cannot be deleted

value:3.14,

enumerable:true, // can enumerate

})

console.log(obj.PI)

(6) Determine whether an attribute belongs to an object

in operator : to determine whether a property belongs to an object.

hasOwnProperty: The method returns a Boolean value indicating whether the object has the specified property in its own properties (that is, whether there is the specified key).

The difference between in and hasOwnProperty?

 in first looks for it inside itself, if it can't find it, it will look for it in its prototype object.

hasOwnProperty will only be found within itself.

operator:

let wc = {

name:"wangcai",

age:100,

say:function(){

console.log("wangwang...")}}

 //console.log("name" in wc) // The key needs to be quoted when it is used outside true

//console.log(wc.hasOwnProperty("say")) //true Both of these can get the properties on the body

in can get the method on the prototype:

var arr = ["a","b","c"]

// arr is an object push is a method push that cannot be found inside arr, so go to its prototype object to find it

arr.push("d")

console.log("push" in arr) // true

console.log(arr.hasOwnProperty("push")) // false

 

The array deduplication of this knowledge point and the number of elements in the statistical array:

Array deduplication:

var arr = [1,2,3,3,1,2,4,5,2,4,5,7,5,7,8];

// function fn(arr){

// var newArr = [];

// // Determine whether each element in the array has been processed

// var o = {}; // {"1":true,"2":true,"3":true}

// for(var i=0; i<arr.length; i++){

// let t = arr[i]; // t represents each element in the old array

// if(o[t]){ }else{

// newArr.push(arr[i])

// o[t] = true;}}

// return newArr; }

// var newArr = fn(arr);

// console.log(newArr) //   [1, 2, 3, 4, 5, 7, 8]

Count the number of elements in an array:

var arr = [1,2,3,3,1,2,4,2,6,2];

function fn(arr){

var obj = {};// {"1":2, "2":3, "3":100} {"1":1,"2":1}

for(var i=0; i<arr.length; i++){

var t = arr[i]

// obj[t] = 1 obj[t] = obj[t]+1

if(obj.hasOwnProperty(t)){

obj[t] = obj[t] + 1

}else{

obj[t] = 1;}}

return obj;}

let res = fn(arr)

// res should contain how many times each element appears res is an object

console.log(res)

Second function (VIP in js, our highlight)

Functions are special in JS:

1) The function we have learned before is just to treat the function as an ordinary function

2) A function can be regarded as a class (constructor) in JS, and the first letter of the function name (class name) is usually capitalized.

Function declaration (this function is just an ordinary function at this time)

function fn(a,b){

 Generate a local execution context (local stack, function stack..)

Formal parameter assignment, declaration promotion, code execution

return a+b;

 }

// console.log(fn(1,2))

3) The role of the class is to create an object

function CreateDog(name, age){

this.name = name;

this.age = age;}

let wc = new CreateDog("wangcai",100);

console.log(wc.name)

console.log(wc.age)

4) The two roles of the function

 Treat the function as a class (constructor):

 Purpose: to create an object

Functions have now two roles:

! Ordinary function --> local execution context

// call the function as a normal function

// function fn(a,b){

// return a+b

// }

// Calling the return value of the function will generate a local execution context

// fn(1,2)

 ! Class (constructor, constructor) ---> new; the difference between treating a function as a class and treating a function as an ordinary function?

As a class, new is required. What is the difference between new and calling functions directly before us?

 1) new will create an object when executing the code, 2) then point this to this object, 3) finally return the address of the object.

// Usually the first letter of the class name will be capitalized

function CreateDog(name,age){

this.name = name;

this.age = age;}

let wc = new CreateDog("wangcai",1000);

console.log(wc.name)

console.log(wc.age)

Notice:

1: Treat functions as classes

 ! The first letter of Fn is capitalized, not mandatory, but it is the default rule of an industry

! It will create an object for us internally and return without us doing

! There is a this in each class, and this refers to the created object

! new must eventually get an object

Big note: the statement after return will not be executed

If you treat a function as a class, then you return a common basic data type of data, which is equivalent to not returning

It internally returns an object

2: If an object is returned in a class: If the function is regarded as a class and an object is returned in the class, the object will eventually overwrite the default object

function Fn(){

this.name = "xxx";

return {

age:666}}

console.log(Fn()); // {age: 666}

let r = new Fn();

console.log(r); // {age: 666}

5) The new objects are all independent:! ! ! !

// When the code executes to CreateDog, do several things:

// Assignment of formal parameters

// promotion of declaration

// code execution

// create an empty object

// Let this point to the empty object

// return this object

// let a = 666; // is a local variable in the local execution context

// this.name = name // Add a name attribute to this object and assign a value

// this.age = age // Add an age attribute to this object and assign it

// this.say = function(){} // Add a say attribute to this object and assign it

function CreateDog(name, age){

let a = 666;

this.name = name;

this.age = age;

this.say = function(){

console.log("wangwang...")}}

let wc = new CreateDog("wangcai",100);

console.log(wc.a) // undefined

console.log(wc.name) // wangcai

// this points to the object you created

let wc1 = new CreateDog("wc1",1);

let wc2 = new CreateDog("wc2",2);

console.log(wc1) // {name: "wc1", age: 1, say: ƒ}

console.log(wc2) // {name: "wc2", age: 2, say: ƒ}

console.log(wc1 === wc2) // false

// new CreateDog can not pass parameters

// When new a class, you can add () or not add (), the difference is that you can’t pass parameters without adding ()

let wc3 = new CreateDog;

console.log(wc3) // {name: undefined, age: undefined, say: ƒ}

instanceof determines whether an object belongs to a class (function, constructor)

function CreateDog(name, age){

this.name = name;

this.age = age;}

let wc = new CreateDog("wangcai",100);

// console.log(wc instanceof CreateDog) // true

6) There are many classes in JS by default.

如:Number, String, Boolean, Array, Object, Math, Date, RegExp...

Basic data types are also objects (instances) belonging to a certain class

instanceof cannot detect basic data types, typeof can detect basic data types, but the detection of reference data types is inaccurate

Both instanceof and typeof have shortcomings for data type detection.

Three JSON: Notation of JavaScript Object Notation JS Object

// Check whether the JSON is legal: http://www.bejson.com/

The essence of Internet access: client: mobile phone, QQ, browser... server: computer, Internet access is the process in which the client requests the server, and the server returns the data you need.

JSON is a data format for communication between the client and the server.

JSON is usually written in two ways:

The form of the array: [{},{},{}]

The form of the object: {}

1) Syntax of JSON data:

1. There are key-value components. 2. Key-value pairs are separated by commas. 3. Put objects in {} and put them in arrays. 4. Keys must also be wrapped in double quotes

where Stu = [

{"id":1,"name":"z3","age":4,"score":"10"},

{"id":2,"name":"z4","age":5,"score":"11"},

{"id":3,"name":"z5","age":6,"score":"12"}

]

var obj = {

name:"wangcai",

age:100,

isSleep:true,

say:function(){

}}

 

2) JSON: JavaScript Object Notation JS object representation

Is a special JS object, JSON is a lightweight data exchange format.

Manipulate JSON: CRUD operation (addition, deletion, modification and query)

where stu = [

{"id":1,"name":"z3","age":4,"score":"10"},

{"id":2,"name":"z4","age":5,"score":"11"},

{"id":3,"name":"z5","age":6,"score":"12"}

]

// visit

console.log(stu[0])

console.log(stu[0].name)

console.log(stu[0]["name"])

 

// Revise

stu[0].score = "100"

console.log(stu[0])

 

// delete

delete this[0].score;

console.log(stu[0])

 

// traverse

for(var i=0; i<stu.length; i++){

// console.log(stu[i])

for(var item in stu[i]){

console.log(stu[i].age)

}}

2) JSON object, JSON string

JSON has two forms: JSON string: it is essentially a string and can only be enclosed in single quotes

JSON string: it is essentially a string and can only be enclosed in single quotes

JSON object: special js object

JSON object

var obj = [{"id":"01","name":"wangcai"}]

JSON string

var obj = '[{"id":"01","name":"wangcai"}]'

How to convert between JSON string and JSON object

Convert JSON object to JSON string

var obj = [{"id":"01","name":"wangcai"}]

let str = window.JSON.stringify(obj)

console.log(str)

 console.log(typeof str)//string

Convert JSON string to JSON object

var obj = ‘[{"id":"01","name":"wangcai"}]’

let str = window.JSON.parse(obj)

console.log(str)

 console.log(typeof str)//Object

Four Prototypes and Prototype Chains

property type prototype

 1) No function (a function is also an object) has a prototype property. prototype is an attribute name, and its attribute value is an object, which we call a prototype object.

2) Many public properties and methods are placed on the prototype object.

3) Each prototype object must have an attribute called constructor. construct is also an attribute name, and its attribute value is the current function itself

4) Each object has an attribute called __proto__, which is also the attribute name, and it points to the prototype object

Func is a class (constructor), essentially a function, and a function is also an object

Every function (function is also an object) has a prototype property

function Func(){

this.name = "xxx"

}

// __proto__ in obj1 points to the prototype object of the class that created the obj1 object.

let obj1 = new Func();

let obj2 = new Func();

Func.prototype.say = function(){

console.log("say...")

}

Access properties in an object:

Access properties in an object

// console.log(obj1.name) // It has a name attribute inside, so go find it inside

// obj1.say() // It doesn't have a say method inside, so go find it in its prototype object

// obj2.say() // It doesn't have a say method inside, so go find it in its prototype object

Object is the top-level class of all objects, also called the base class. So Object.prototype.__proto__ points to itself.

 Since it doesn't make sense to point to itself, its default value is null

Prototype chain: If you want to find an attribute, first look for it inside yourself (private), if there is, use it, and don't look backwards.

If not, follow __proto__, find the properties on the class prototype object, and keep looking up until you find Object.prototype.

// Test questions

console.log(obj1.say === obj2.say) // true

console.log(Func.prototype.say === obj1.say) // true

console.log(obj1.__proto__.say === Func.prototype.say) // true

console.log(obj1.__proto__ === Func.prototype) // true

console.log(obj1.name === obj2.name) // true

console.log(obj1 instanceof Func) /// true

console.log(obj1 instanceof Object) // true

 

Prototype and prototype chain (about built-in objects in js)

The built-in object Array (constructor), arr is called an object.

var arr1 = new Array("a","b","c")

var arr2 = new Array("d","e","f")

console.log(Array.prototype === arr1.__proto__) // true

console.log(Array.prototype.push === arr1.push) // true

console.log(arr1 === arr2)//false

console.log(arr1 instanceof Array)//true

console.log(arr1 instanceof Object)//true

Prototype chain:

console.dir(arr1.__proto__)

console.dir(arr1.__proto__.__proto__)

console.dir(arr1.__proto__.__proto__.__proto__) // null

Five: this problem

// ------------------ Situation 1: this represents the event source in the listener

// DOM

var btn = document.getElementById("btn")

// btn calls the event source on is the event type in the prefix click

// function(){} event handler (listener)

btn.onclick = function(){

// alert(this) // [object HTMLButtonElement]

console.log(this)

// alert("Successful login...")

}

//------------------ Situation 2: In non-strict mode, this appears in ordinary functions, indicating window; in strict mode, it indicates undeeeind

function f(){

console.log(this) // Window }

f()

function f(){

"use strict"

console.log(this) // undefined}

f()

// ------------------ Situation 3: this appears in a method of an object, indicating the current object

var obj = {

name:"wangcai",

say:function(){

console.log(this) // {name: "wangcai", say: ƒ}}}

obj.say();

// ------------------ Situation 4: this appears in a class, indicating that it points to a new object

function Func(){

 this.name = "xxx";

console.log(this) // {name: "xxx"} }

let obj1 = new Func();

// ------------------ Situation 5: In the global scope, this means window

console.log(this) // Window

Note: The this point in the method is uncertain, whoever calls the method, this is who

Note: Whether it is a private method or a public method, whoever calls the method, this is who

Six: About anonymous functions

assign an anonymous function to f

// var f = function(){}

g is the function name For function expressions, you can specify the function name

// var f = function g(){console.log("haha...")}

// f()

// cannot call a function by its function name in a function expression

// g() // g is not defined

g is the function name, which can be used in the function body. This function can be called through g(), but there will be an infinite loop if there is no exit. Assigning basic data types to g has no effect, and assigning reference data types to g has no effect.

For a function expression, it can have a function name, the function cannot be called by the function name outside the function, the function name or function call can be used inside the function (infinite loop), and the function name cannot be reassigned

Seven: call method

--------------------------------------------- A preliminary understanding of the call method

1) call is a method on the prototype object of the function

 2) A function .call, you can call this function

 3) this in f.call() f means window

 4) f.call(obj) this in f means obj

// Demand, want to call f function through obj, how to do it?

 Method 1: Use the function as an attribute of obj: hang this function on the attribute of obj

// obj.f = f;

// obj.f(); // f....

Method 2: Do not use the properties of obj, and delete them when they are used up

// delete obj.f;

// console.log(obj) // {name: "wangcai"}

Method 3: use call to let obj borrow the f method, this in the f method points to obj

f.call(obj);

console.log(obj) // {name: "wangcai"}

----------------- In JS, the point of this can be changed by calling

 In-depth understanding of the first parameter of the call method call ----------------- the first parameter

// The purpose of fn.call is to let fn execute and change the point of this in fn

// In JS, the point of this can be changed by calling

function fn(){

console.log(this)

console.log("fn...")

}

// fn() The this in it represents window

// fn.call(); // this in fn means window

// fn.call(123) // this in fn means Number {123}

// fn.call("hello") // this in fn means String {"hello"}

// fn.call(true) // this in fn means Boolean {true}

// fn.call({}) // {}

// let obj = {name:"xxx"}

// fn.call(obj) // {name: "xxx"}

// ----------------- In-depth understanding of other parameters of the call method call

 The call method supports parameter passing. From the second actual parameter of the call method, it is the list of actual parameters.

let r = fn.call(obj,1,2)

console.log(r)

// ----------------- In-depth understanding of other parameters of the call method call ----------------------

// Summarize:

// 1) call is an attribute on the prototype object of the function

// 2) Any function can be .call

// 3) When a function is called, the function is executed, and this in the function points to the first actual parameter in the call

// 4) If the call method has no actual parameters, this function can also be executed, but this in the function means window (in non-strict mode), and in strict mode, it is undefined

// 5) If the first parameter of call is null, in non-strict mode, this in the function means window, in strict mode, this means null

// 6) When the function .call() is executed, the function will definitely be executed, and parameters can be passed to the function. The actual parameters starting from the second parameter of the call will be passed to this function

//The principle of handwritten call is not described here.

Eight: apply method

The only difference between apply and call is the difference in passing parameters. call is to pass parameters one by one, and apply is to pass parameters in the form of an array . The principle of the apply method is not written here.

function fn(a, b){

console.log(this);

return a+b;

}

var obj = {name:"xxx"}

// fn.call(obj,11,22)

let res = fn.apply(obj,[11,22])

console.log(res)

 

Nine: bind method

1) Like call/apply, you can change this in the function.

 2) Unlike call/apply, bind will not let the previous function execute. Need to call manually.

// ----------------- bind application scenarios

<button id="btn">login</button>// btn calls event source click calls event type function(){} calls listener

var btn = document.getElementById("btn");

// btn.onclick = function(){//register click event

// console.log("....")

// }

 JS is single-threaded, and can only execute one task at a time. It first executes the synchronous task, and then executes the asynchronous task when the asynchronous task occurs.

// console.log("start")

// function fn(){

// console.log("666")

// }

// // The event is an asynchronous task

// btn.onclick = fn;

// console.log("end")

// function fn(){

// console.log(this)

// }

// btn.onclick = fn;

 

// Requirement: I don't want this in the listener to represent the event source, but I want this to represent obj

// var obj = {name:"xxx"}

// function fn(){

// console.log(this)

// }

// btn.onclick = fn.call(obj) // It is not appropriate to use call at this time, because call will be executed immediately

// // Requirement: I don't want this in the listener to represent the event source, but I want this to represent obj

// var obj = {name:"xxx"}

// function fn(){

// console.log(this)

// }

// btn.onclick = function(){

// fn.call(obj)

// }

 Requirement: I don't want this in the listener to represent the event source, but I want this to represent obj

var obj = {name:"xxx"}

function fn(){

console.log(this)

}

btn.onclick = fn.bind(obj);

The principle of bind is not described here

Ten: Determine whether an attribute is a public attribute (mentioned in the interview question)

An interview question:

function fn1(){console.log(1)}

function fn2(){console.log(2)}

fn1.call(fn2); //1

fn1.call.call(fn2); //2

Function.prototype.call(fn1) //无

Function.prototype.call.call(fn1) //1

Eleven: Inheritance and principles are mentioned in enterprise interview questions:

Four ways to find the maximum and minimum values ​​in an array:

Based on prototype chain inheritance:

Based on call or apply inheritance:

Composition inheritance:

Perfect inheritance:

Encapsulate a method to implement inheritance:

Implementation of the new principle:

Implementation of the instanceof principle:

call principle:

apply principle:

bind principle:

myflat principle:

push principle:

// push principle Array.prototype.push = function(value){

// this[this.length] = value;

// this.length++;

// return this.length;

// }

 

 

 

Guess you like

Origin blog.csdn.net/zwy1231/article/details/103652080