Search

11/14/2008

call() and apply()

obj.method.call(another_obj, param1, param2)
obj.method.apply(another_obj, [param1, param2])

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

>>> f(1, 2, 3, 4, 5, 6)
2,3

[].slice.call can also be Array.prototype.slice.call

function one() {
alert(1);
return function() {
alert(2);
}
}
>>> my = one(); // alerts 1
>>> my(); // alerts 2

Adding properties to the function objects, e.g. cache, 'coz functions are objects

function myFunc(param){
if (!myFunc.cache) {
myFunc.cache = {};
}
if (!myFunc.cache[param]) {
var result = {}; // …
myFunc.cache[param] = result;
}
return myFunc.cache[param];
}

a is private, sayAh() is privileged

function MyConstr() {
var a = 1;
this.sayAh = function() {
return a;
};
}

>>> new MyConstr().sayAh();

沒有留言: