1. 程式人生 > >js核心概念之apply與call

js核心概念之apply與call

apply

/**
    _layout: function (pjs, node, js) {
		var ar = [node]; for (var i = 0; i < js.length; i++)ar.push(js[i]);

		//發生resize事件後,所有相關節點調整
		BindUIEvent(pjs, node, "resize", function () {
			doLayout.apply(node, ar);
		});
    }
 */

function doLayout(wgt, pct, pos, off) {
    console.log("-----wgt:" + JSON.stringify(wgt));
    console.log("-----pct:" + pct);
    console.log("-----pos:" + pos);
    console.log("-----off:" + off);
}

let node = { a: "aaa" }
var arr = [node];

let js = [
    [0.08, 0.08], [0.12, 0.825], [0, 0]
];

for(let i = 0; i < js.length; i++){
    arr.push(js[i]);
}

doLayout.apply(node, arr);

/**
$ node test.apply.js
-----wgt:{"a":"aaa"}
-----pct:0.08,0.08
-----pos:0.12,0.825
-----off:0,0
總結:apply第一個引數為this,然後將陣列中引數依次賦值給function的引數。 因此apply比call直觀一點吧
 */

call

function doLayout(wgt, pct, pos, off) {
    console.log("-----wgt:" + JSON.stringify(wgt));
    console.log("-----pct:" + pct);
    console.log("-----pos:" + pos);
    console.log("-----off:" + off);
}

let node = { a: "aaa" }


doLayout.call(node, node, [0.08, 0.08], [0.12, 0.825], [0, 0]);

/**
-----wgt:{"a":"aaa"}
-----pct:0.08,0.08
-----pos:0.12,0.825
-----off:0,0

總結:call第一個引數為this,從第2個引數開始,會依次賦值為function的引數
 */