2016年6月20日 星期一

javascript call 和 apply的差別


在js裡,function也是物件,有兩個預設的方法用來觸發作用,call和apply,兩個方法的第一個參數都是指定function的owner,也就是this代表的物件

var myObject={}, myArray=[10,2];

function test (a,b) {
     console.log(this);
     return a*b;
}

test.call(myObject,10,2) //this為myObject return 20

test.apply(myObject,myArray) //this為myObject return 20


call和apply的差別僅在於參數的給定方式,call一對一傳入參數,apply則是傳入一個參數陣列

w3schools上對於strict模式和non-strict對這兩個方法的影響之說明:

In JavaScript strict mode, the first argument becomes the value of this in the invoked function, even if the argument is not an object.

In "non-strict" mode, if the value of the first argument is null or undefined, it is replaced with the global object.

function除了兩個內建的觸發方法之外,還有1個內建的屬性和1個方法,arguments.length屬性和toString()方法:

arguments.length屬性傳回接收到的參數數量

function myFunction(a, b) {
    return arguments.length;
}

myFunction(5,6) //傳回2

toString()方法將function以文字形態傳回

function myFunction (a, b) {
        return a * b;
}

var txt = myFunction.toString();

console.log(txt)

// console輸出如下內容

function myFunction (a, b) {
        return a * b;
}

沒有留言:

張貼留言