Goto JS apply 方法

Apply方法

應用某一對象的一個方法,用另一個對象替換當前對象。

apply([thisObj[,argArray]])

參數

thisObj

可選項。將被用作當前對象的對象。

argArray

可選項。將被傳遞給該函數的參數數組。

說明

如果 argArray 不是一個有效的數組或者不是 arguments 對象,那麼將導致一個 TypeError。

如果沒有提供 argArraythisObj 任何一個參數,那麼 Global 對象將被用作 thisObj, 並且無法被傳遞任何參數。


e.g

function f() {
				var args = [].slice.call(arguments, 1, 3);
				return args;
			}

			var one = {
				name:'object',
				say:function (greet) {
					return greet + ', ' + this.name;
				}
			};

			// test
			console.log(one.say('hi')); // "hi, object"

			var two = {
				name:'another object'
			};
			
			// apply two to original object one.
			console.log(one.say.apply(two, ['hello'])); // "hello, another object"


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