I always assumed that some_function(...) was exactly the same as some_function.call(this, ...). This seems not to hold true for calls in constructors / an object construction context:
function Class(members, parent) {
function Ctor(value) {
members.__init__.call(this, value);
return this;
};
Ctor.prototype = members;
Ctor.prototype.__proto__ = parent.prototype;
return Ctor;
}
var Base = Class({
__init__: function(value) {
this.value = value;
}
}, {});
var Child = Class({
__init__: function(value) {
// Base(value*2); ← WON'T WORK AS EXPECTED
Base.call(this, value*2); // works just fine
}
}, Base);
In Child.__init__ it in necessary to use the explicit call to Base.call(this, value). If I don’t use this lengthy expressing, this would name the global object (window in browsers) in the called base constructor. With "use strict" an error would be thrown as there is no global object in strict mode.
Can someone please explain why I have to use Func.call(this, ...) in this example?
(Tested with Node.js v0.6.12 and Opera 12.50.)
Calling a function with
.callis different from just invoking it with(). With.callyou explicitly set the value ofthisfor the call in the first argument. With normal invocation, thethisvalue will implicitly be the global object orundefined, depending on whether strict mode is enabled or not.See .call
That’s not true, they are never the same. You are probably confusing it with calling a function as a property of some object.
obj.method()will mean thatobjis the value ofthisfor the method call and it would be effectively the same asobj.method.call(obj).