JavaScript基礎對象---Function

一、Function實例屬性

1.length屬性:指明函數的形參個數

形參的數量不包括剩餘參數個數,僅包括第一個具有默認值之前的參數個數

    console.log(Function.length); // 1
    console.log(Function.prototype.length); // 0

    console.log((function()        {}).length); // 0
    console.log((function(a)       {}).length); // 1
    console.log((function(a, b)    {}).length); // 2

    console.log((function(...args) {}).length); // 0, 其餘參數不會被計入
// 0, rest parameter is not counted

    console.log((function(a, b = 1, c) {}).length); // 1, 僅包括第一個具有默認值之前的參數個數

    console.log((function(a = 1, b, c) {}).length); // 0
    console.log((function(b, a = 1, c) {}).length); // 1
    console.log((function(b, c, a = 1) {}).length); // 2

2.function.name 屬性返回函數實例的名稱

    let o = {
        get foo(){},
        set foo(x){}
    };
    let descriptor = Object.getOwnPropertyDescriptor(o, "foo");
    console.log(descriptor.get.name); // "get foo"
    console.log(descriptor.set.name); // "set foo";

二、Function實例方法

 

1.apply() 方法調用一個函數, 其具有一個指定的this值,以及作爲一個數組(或類似數組的對象)提供的參數

語法:func.apply(thisArg, [argsArray])
參數:
     thisArg  可選的,在 func 函數運行時使用的 this 值
        需要注意的是,使用的 this 值並不一定是該函數執行時真正的 this 值,如果這個函數處於非嚴格模式下,則指定爲 null 或 undefined 時會自動替換爲指向全局對象(瀏覽器中就是window對象),同時值爲原始值(數字,字符串,布爾值)的this會指向該原始值的包裝對象
     argsArray  可選的,一個數組或者類數組對象,其中的數組元素將作爲單獨的參數傳給 func 函數
        如果該參數的值爲null 或 undefined,則表示不需要傳入任何參數。從ECMAScript 5 開始可以使用類數組對象

    let numbers = [5, 6, 2, 3, 7];

    let max = Math.max.apply(null, numbers); // 7
    let min = Math.min.apply(null, numbers); // 2
    console.log(max,min);

2.bind()方法創建一個新的函數, 當被調用時,將其this關鍵字設置爲提供的值,在調用新函數時,在任何提供之前提供一個給定的參數序列

語法:fun.bind(thisArg[, arg1[, arg2[, ...]]])
參數:
     thisArg
        當綁定函數被調用時,該參數會作爲原函數運行時的 this 指向
     arg1, arg2, ...
        當綁定函數被調用時,這些參數將置於實參之前傳遞給被綁定的方法

返回值:返回由指定的this值和初始化參數改造的原函數拷貝

    let object = {
        x: 9
    };
    let module = {
        x: 81,
        getX: function (){
            return this.x;
        }
    };
    console.log(module.getX()); // 81
    let retrieveX = module.getX.bind(object);
    console.log(retrieveX()); // 9

3.call() 方法調用一個函數, 其具有一個指定的this值和分別地提供的參數(參數的列表)

語法:fun.call(thisArg, arg1, arg2, ...)
參數:
     thisArg  在fun函數運行時指定的this值
        需要注意的是,指定的this值並不一定是該函數執行時真正的this值,如果這個函數處於非嚴格模式下,則指定爲null和undefined的this值會自動指向全局對象(瀏覽器中就是window對象),同時值爲原始值(數字,字符串,布爾值)的this會指向該原始值的自動包裝對象

     arg1, arg2, ...  指定的參數列表

    function Product(name, price) {
        this.name = name;
        this.price = price;
    }
    function Food(name, price) {
        Product.call(this, name, price);
        this.category = 'food';
    }
    console.log(new Food('cheese', 5).name); // cheese

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章