Object oriented is a platitude topic, how to use JavaScript to achieve object oriented?

This article will start from JavaScript objects, a full range of how to elaborate JavaScript objects, there must be you do not know!

15 examples, a comprehensive summary of how Javascript is object-oriented

Object oriented

1. Detect attributes

Object.hasOwnProperty("name")           // Only detect itself, not the prototype

"name" in a                             // Check whether the prototype chain in A contains the name attribute, check itself and the prototype
Copy the code

2. Operation

delete Object.AttributeName

Object. Assign (object1,object2) Merges two objectsObject.keys()

Object.values()

Object.entries() gets an array, usually a two-dimensional array d'd'd'd for of 'is for iterating on an ObjectCopy the code

3. Prototype

Object.setPrototypeOf(son,parent)
Copy the code
// Set the prototype of A to B
let a = {
    name : "a"
}
let b = {
    name : "b"
}
Object.setPrototypeOf(a,b)
Copy the code

1. Deconstruction of multi-layer objects

Make sure the left and right structures are the same

let hd = {
    name : "Backer".lesson : {
        title : "Javascript"}}let {name,
    lesson : {title}
} = hd;
console.log(name,title);

Copy the code

2. Deconstruct assignment to implement configuration merge

Merge configuration items using the default parameters of the object

function creatEle(options = {}){
    let {width = 200, height = 200 , backgroundColor = "green"} = options
    let divs = document.createElement("div");

    divs.style.width = width + "px";
    divs.style.height = height + "px";
    console.log(width,height,backgroundColor);
    divs.style.backgroundColor = backgroundColor

    document.body.appendChild(divs)
}
creatEle();

Copy the code

3. Object and prototype chain attribute detection example

let arr = ["Array"."houdunren"]
console.log(arr.hasOwnProperty("length")) this method detects itself, not the prototypeconsole.log("length" inArr) this method detects both prototype and itselfCopy the code

4. Calculate the use of attributes and assign

Convert an array to an object

let lessons = [
    {
        name : "CSS tutorial".category : "css"
    },
    {
        name : "PHP tutorial".category : "php"
    },
    {
        name : "The Java tutorial".category : "java"},]let obj = lessons.reduce((obj,cur,index) = > {
    obj[`${cur.category}-${index}`] = cur;
    return obj
},{})

console.log(obj);

Copy the code

5. Multiple operation methods for shallow copy of objects

Shallow copy: The format of an object in an object is not copied

let obj = {name : "".age:18.json: {}}Copy the code

Method 1 :(for-in) :

let obj = {
    name : "houdunren.com".url : "hdcms"
}
let hd = {}

for (const key in object) {
    hd[key] = obj[key]; 
}

Copy the code

Way 2 (Object. The assign ()) :


let obj = {
    name : "houdunren.com".url : "hdcms"
}
let hd = Object.assign({},obj)
console.log(hd);
Copy the code

Method 3: Expand the syntax

6. Deep copy multi-level analysis

We copy obj to HD, but when we pass user, since user is an object, we pass user by address. Obj and HD share the same user, which is not what we want

let obj = {
    name : "houdunren.com".user : {
       age : 18}}lethd = {... obj}console.log(hd);
Copy the code

We can define deep-copy functions

function copy(data){
    // Determine whether to receive data from an array or an object
    let obj = data instanceof Array ? [] : {}
    // Iterate over the array
    for (const [k,v] of Object.entries(data)) {
        obj[k] = typeof v == "object" ? copy(v) : v;
    }
    return obj;
}
Copy the code

7. Create objects using factory functions


        function FactoryPerson(name,age,address) {
            // Create a new object
            var obj = new Object(a);// Add attributes to the object
            obj.name = name;
            obj.age = age;
            obj.address = address;
            obj.sayHello = function () {
                console.log("I'm %s, and have %d years old. By the way, I live in %s".this.name,this.age,this.address)
            }

            // Return a new object
            return obj;
        }
Copy the code

8. Object encapsulation and abstraction

Properties defined using this are externally accessible, properties defined by variables are not (implement abstraction)

function User(name,age){
    this.name = name;
    this.age = age;
    let show = function(){
        console.log(name + age); }}let hd = new User("Xiang".18)
hd.show();

Copy the code

9. Attributes of the object

const usr = {
    name : "houdunren".age : 18
}
Copy the code

1. Obtain attribute features:

Object.getOwnPropertyDescriptor(user,name)
Object.getOwnPropertyDescriptors(user)
Copy the code

2. Modify attribute features:

Object.defineProperty(user,name,{config})
Object.defineProperties(user,{})
Copy the code

3. Attribute operation:

Object.preventExtensions(user);         // Disallow adding attributes to objects
Object.isExtensible()                   // Check whether the object is extensible
Object.seal()                           // Closed object, cannot be added, cannot be configured
Object.isSealed()                       // Check whether it is closed
Object.freeze()                         // Freeze the object, which cannot be modified, added, or configured
Objcet.isFrozen()                       // Determine whether to freeze
Copy the code

10. Use set,get accessors to protect data

The accessor has a high priority

const user = {
    data : {name : "houdunren" , age : 18},
    set age(value) {if(typeofvalue ! ="number" || value > 100 || value < 10) {console.log("The input value is not correct.")}this.data.age = value;
    }
    get age() {return this.data.age;
    }
}
user.age = 5;
Copy the code

11. Use the token to save login information

let Request = {
    set token(content) {localStorage.setItem("token",content);
    },
    get token() {let token = localStorage.getItem("token");
        if(! token){ alert("Please log in.")}return token;
    }
}
Request.token();
console.log(Request.token);
Copy the code

12. What is Proxy interception

Accessors are proxies for properties of objects, and proxies are like intermediaries for buying houses. They do not operate objects directly

let obj = {
    name : "Ocean View Room".price : 18500
}
// Create a new agent, tell him I want to represent the ocean view room
let proxy = new Proxy(obj,{
    get(obj,property){
        return obj[property]
    },
    set(obj,property,value){ obj[property] = value; }}); proxy.name ="Sea View Room 2"
console.log(proxy);
console.log(proxy.price)
Copy the code

13. Use the proxy. apply Proxy function

Proxy.apply(func,obj,args)

function factorial(num){
    return num === 1 ? 1 : num * factorial(num-1);
}
let proxy = new Proxy(factorial,{
    // The first is the function to be propped, the second is the scope of the object, and the third is the argument to be passed (must be in array form)
    apply(func,obj,args){
        console.time("run")
        func(args)
        console.timeEnd("run")}})Copy the code

14. Arrays are intercepted by proxies

let lessons = [
    {
        title : The CSS class "".number : "1084350607"
    },
    {
        title : "The Java tutorial".number : "1091525714"
    },
    {
        title : "Full PHP Teaching".number : "1091525714"}]let proxy = new Proxy(lessons,{
    get(array,key){
        let number = array[key].number;
        const length = 3;
        array[key].number = number.length >= length 
            ? number.substr(0.3) + "*".repeat(number.length-length) 
            : number;
        returnnewAry; }});console.log(proxy[2]);
Copy the code

15.VUEJS data binding implementation, using Proxy to achieve two-way data binding

It is equivalent to the landlord telling the agent that the house price has changed, and the agent tells multiple users that the price has changed.

    <input type="text" data_title = "title">
    <input type="text" data_title = "title">
    <div data_title = "title">Update the data</div>
Copy the code
function View(){
    let ele = document.querySelectorAll("[data_title]")
    let proxy = new Proxy({}, {set(obj,property,value){
           ele.forEach(item= > {
               item.value = value
           })              
        },
        get(obj,propert){}});this.init = function(){        
        ele.forEach(item= > {
            item.addEventListener("keyup".function(){
                proxy[this.getAttribute("data_title")] = this.value; }}})})new View().init()
Copy the code