prototype - Why is apply not already bound to functions in Javascript? -
assume, sake of question, want able create function in javascript appends of elements of 1 array array. 1 way achieve this, if have access destination array, say:
var destination = [1,2,3]; var source = [4,5]; array.prototype.push.apply(destination, source); console.log(destination); // [1,2,3,4,5] now, since array.prototype.push.apply pretty ugly, want alias nicer, like:
var pushall = array.prototype.push.apply; which should able call 2 arguments, context (destination) , array of arguments (source). however, when try use alias, happens:
pushall(destination, [6,7]); typeerror: function.prototype.apply called on [object global], object , not function so apply function not bound push, led me try this:
var pushall = function.prototype.apply.bind(array.prototype.push); pushall(destination, [6,7]); console.log(destination); // [1,2,3,4,5,6,7,8] which works fine. question is, why have bind push method apply? shouldn't array.prototype.push.apply bound apply? why calling under different name result in calling on unbound context?
why have bind push method apply?
it's other way round: have bind apply method array push function - can bind other functions well! otherwise apply doesn't know which method apply arguments.
function.prototype.apply.bind(array.prototype.push); call bind function on apply function push argument, argument on apply bound. resulting function pushall will, when called, invoke apply on push function, , pass it's argument (the array , arguments array) it.
shouldn't array.prototype.push.apply bound apply?
nope. javascript designed bind context @ call of function, not when it's being referred property - there no implicit binding on property access. otherwise array.prototype.push bound array.prototype, before call function methods bind/apply on , try use different context.
why calling under different name result in calling on unbound context?
it's not different name, different style. (unbound) functions this value set object when called as method on it, i.e. when reference called function property access: destination.push().
this allows great flexibility, can "borrow" functions object , call them on other objects, still being same (unbound) function. rather impossible in languages function objects no first-class objects.
if functions (even though meant methods) called plain functions (pushall()), this value undefined (unless in sloppy mode). read more on this keyword @ mdn.
Comments
Post a Comment