JavaScript 物件

與其他程式語言類似,javascript 物件是鍵值對的集合,其中每個鍵是一個字串,每個值可以是任何資料類型。

建立 JavaScript 物件的方法

  1. 物件字面量表示法
The simplests way that you will use 98% of time.

        const scorcism = {
            name: "Abhishek",
            age:21
        }
The key-value pairs are enclosed within curly braces `{}`

  1. 使用new關鍵字
Creating objects with constructor functions and the `new` keyword. You will use this only 1.8% of the time

        function About(name, age, city) {
            this.name = name;
            this.age = age;
            this.city = city;
        }   

        const me = new About("Abhishek", 21, "Mumbai"); 

“new”建立一個包含內部“this”的物件。如果省略“new”,則這是全域上下文,因此您的屬性是在物件外部建立的。 ~埃克哈德

  1. 使用 Object.create()
This method allows creating a new object with specified prototype object. 

You will use this only 0.2% of the time 

        const aboutData = {
            greet:function(){
                    return `Hello, my is ${this.name}`; // {this.name} is the key of this object
                }
        }
        const me = Object.create(aboutData);
        me.name = 'Abhishek'
        me.age = 21;
Don't worry much about this :)

存取物件屬性

JS 物件的屬性可以使用點表示法和括號表示法來存取。

    const me = {
            name: "Abhishek",
            age:21
    }
    console.log(me.name);   
    console.log(me["age"]);

嘗試執行程式碼片段。

(每個控制台日誌後面的undefinedconsole.log函數本身的回傳值。放鬆,沒什麼好擔心的🕺)

物件原型和繼承

JS 的核心是原型的概念。 JS 中的每個物件都與一個原型物件相關聯,原型物件充當該物件的藍圖

簡而言之;物件原型充當建立新物件的模板。

這個原型物件包含所有從它建立的實例都可以存取的屬性和方法。

繼承是透過物件的原型連結來實現的。

考慮我們上面使用的Object.create() 。它是建立新物件的方法。

靜態方法

(嘗試😃)

  1. 物件.keys()
Returns an array of a given object's own enumerable property **names**. 

TL;DR Object.keys() method will return list of keys. 

**NOTE:** Own enumerable refers to the properties of an object that are both owned by the object itself (Not inherited from its property chain) 

        const aboutMe= {
            name: "Abhishek",
            age:21
        }
        let aboutMeKeys = Object.keys(aboutMe);
        // Expected Output: [ 'name', 'age' ]
  1. 物件.values()
Return an array of a given object's own enumerable property **values**.

TL;DR Object.values() method will return list of values.

                const aboutMe= {
                    name: "Abhishek",
                    age:21
                }
                let aboutMeKeys = Object.values(aboutMe);
                // Expected Output: [ 'Abhishek', 21 ]
  1. 物件.分配()
Copies the values of all enumerable own properties from one or more source objects to a target object.

        const target = {age: 21}
        const source = {name: "Abhishek"}
        const merged = Object.assign(target, source);
        console.log(merged)
        // Expected Output: { age: 21, name: 'Abhishek' }
**Note:** You can add any number of source args. 

**target** will contain the modified object.

        console.log(merged === target)
        // Expected Output: true
  1. 物件.create()
Create new object, using an existing object as the prototype.

        const me = {
              name: "Abhishek",
              eatsAppleDaily: false,
              printAbout: function(){
                console.log(`I am ${this.name}. and I ${this.eatsAppleDaily ? "eat" :"don't eat"} 
                                apple daily.`);
              }
            };

        // Creating a myFriend Object inheriting from me. 
        const myFriend = Object.create(me); // He is my child now😃.  

        myFriend.name = "Ladoo";
        myFriend.eatsAppleDaily = true;

        console.log(me.printAbout());
        // Expected Output: I am Abhishek. and I don't eat apple daily.
        console.log(myFriend.printAbout());
        // Expected Output: I am Ladoo. and I eat apple daily.
  1. 物件.entries()
Return array of he given object's own enumerable string-keyed property key-value pair😒.

It returns an array where each element is a key-value pair of the object. Each key-value pair is represented as an array with two elements: the key as the first element and the corresponding value as the second element.

        const me = { name:"Abhishek", age:21 }
        console.log(Object.entries(me))
        // Expected output: [ [ 'name', 'Abhishek' ], [ 'age', 21 ] ]
  1. Object.fromEntries()
Object.fromEntries transforms a list of key-value pairs into an object.

TL;DR Oppsite of Object.entries().

        const me = [ [ 'name', 'Abhishek' ], [ 'age', 21 ] ]
        console.log(Object.fromEntries(me))
        // Expected output: { name: 'Abhishek', age: 21 }
  1. 物件.freeze()
    The Object.freeze() is a method that "freezes" an object. 

When you freeze an object, you prevent new properties from being added to it, existing properties from being removed or changed, and also prevent the prototype from being changed.

            const me = { name:"Abhishek", age:21 }
            Object.freeze(me); // Freezing the object
            me.name = "scorcism";
            me.age = 22;
            console.log(me) 
            // Expected output: { name: "Abhishek", age: 21 }
Changes are not affected to the object

  1. 物件.isFrozen()
     Determines if the object is frozen

        const me = { name:"Abhishek", age:21 }
        Object.freeze(me); 
        console.log(Object.isFrozen(me))
        // Expected output: true
  1. 物件.seal()
Object.seal() is a method that "seals" an object.

Sealing an object prevent new properties from being added to it and marks all existing properties an non-configurable (i.e prevent them from bein deleted or theri attributes from being changed).

         const me = { name:"Abhishek", age:21 }
         Object.seal(me); 
        me.name = "scorcism"; // This change will be affected 
        delete me.age; // This deleting will not take effect
        console.log(me)
        // Expected Output: { name: 'scorcism', age: 21 }
**Note:** `Object.freeze()` prevents any changes to the object, while `Object.seal()` allows changes to existing properties but prevents addition or removal of properties.

  1. 物件.isSealed()
        Determines if an object is sealed.

        const me = { name:"Abhishek", age:21 }
         Object.seal(me);   
         console.log(Object.isSealed(me));
         // Expected output: true

繼承靜態方法

在轉向實例靜態方法之前,讓我們先了解一下物件中的this關鍵字

假設我們有一個物件

    const person = { name: 'Abhishek' };

所以如果我們在物件中加入一個函數; this將引用同一物件的所有屬性

    const person = { 
        name: 'Abhishek',
        sayMyName: function() {
            return `My name is ${this.name}`;
        }
    };

    console.log(person.sayMyName());
    // Expected Output: My name is Abhishek

正如您在這裡所觀察到的, this.name被替換為鍵name值。

現在您已經了解了this關鍵字的用例,讓我們繼續進一步

1..原型.bind()

bind()方法建立一個新函數,在呼叫該函數時,會將其this關鍵字設定為提供的值。

當我們想要從一個物件借用一種方法並在其他物件的上下文中使用它時,這非常有用,

    function sayMyName (){
        return `My name is ${this.name}`
    }

    const person = { 
        name: 'Abhishek',
        sayMyName: sayMyName
    };

    console.log(person.sayMyName());
    // Expected Output: My name is Abhishek

    const person2 = {
        name: 'Walter'
    }

    const person2NameFunc = sayMyName.bind(person2);

    console.log(person2NameFunc());
    // Expected Output: My name is Walter

對於 person2NameFunc,person 物件this.name取自 person2 物件,因為我們已將sayMyName函數與 person2 物件綁定。

2..原型.call()

call()方法用於呼叫具有給定this值和單獨提供的參數的函數。

        function introduce(language) {
              console.log(`I code in ${language}. My name is ${this.name}.`);
        }

        const mySelf = {
            name: "Abhishek"
        }

        introduce.call(mySelf, 'Java');
        // Expected output: I code in Java. My name is Abhishek.

在這裡,介紹函數採用語言參數並記錄有關語言和人名的資訊。

call()方法用於以 mySelf 物件作為 this 值來呼叫此函數,從而允許存取其屬性。

與使用指定的this值建立新函數的bind()不同, call()直接使用指定的this值以及各個參數來呼叫該函數。

3..原型.apply()

apply()方法與call()類似,但它不是單獨接受參數,而是以陣列形式接受參數。

        function add(...args){
            let sum = args.reduce((acc, curr)=> acc + curr, 0 );
            console.log(sum);
        }
        const numbers = [1,2,3,4,5];
        add.apply(null, numbers)
        // Expected output: 15

何時使用呼叫、綁定和應用

  • call :當您想要立即執行函數並指定this應該引用的內容時,請使用call

  • bind :當您想要建立一個新函數,該函數在稍後執行時具有預先確定的this值時,請使用bind

  • apply " 當您有要傳遞給函數的參數陣列時,請使用apply


PS:之所以到處用我的名字,是因為在閱讀時,每當你看到我的名字時,你都會傾向於嘗試用你的名字來稱呼它。

這些是最常用的,您可以 在此處探索更多訊息


如果這篇文章對您有幫助,請留下喜歡、關注或其他任何東西 🙂。

您可以在LinkedInGitHubDev.tohashnode上關注我。

再見🍕


原文出處:https://dev.to/scorcism/objects-in-js-complete-guide-3gl8


共有 0 則留言