Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

apply() Function ใน JavaScript ใช้ทำอะไร

ปกติ objects มี methods และ properties ของตัวเอง ใช้ apply() สร้างเมธอดที่เข้าถึง objects หลายตัวรวมกันได้

apply() ทำงานคล้าย call() แต่ต้องส่ง array-like variables ใช้ apply()

ตัวอย่าง: เรียกหลาย elements แยกกัน ใช้ call() ไม่ต้อง apply()

ตัวอย่างที่ 1 (ใช้ call)

<html> <body> 
    <script> 
        var obj = {num: 10}; 
        var mul = function(i, j, k){ 
            return this.num * i * j * k; 
        }; 
        document.write(mul.call(obj, 6, 3, 4)); 
    </script> 
</body> </html>

ผลลัพธ์

720

ตัวอย่างที่ 2: ส่ง array แทน call() คืน NaN แต่ apply() คืนค่าถูก เพราะ call() เข้าถึง array ไม่ได้

ตัวอย่างที่ 2 (Array argument)

<html> <body> 
    <script> 
        var obj = {num: 10}; 
        var mul = function(i, j, k){ 
            return this.num * i * j * k; 
        }; 
        var array = [6,3,4]; 
        document.write(mul.call(obj, array)); 
        document.write("<br>"); 
        document.write(mul.apply(obj, array)); 
    </script> 
</body> </html>

ผลลัพธ์

NaN 720