javascript - Why does storing a reference to a function then calling the function cause 'this' to have a context of window? -
i reading tutorial @ can understand _.bind , _bindall: http://blog.bigbinary.com/2011/08/18/understanding-bind-and-bindall-in-backbone.html
the website has next code
function developer(skill) { this.skill = skill; this.says = function(){ alert(this.skill + ' rocks!'); } } var john = new developer('ruby'); john.says(); //ruby rocks!
vs
function developer(skill) { this.skill = skill; this.says = function(){ alert(this.skill + ' rocks!'); } } var john = new developer('ruby'); var func = john.says; func();// undefined rocks!
why storing reference function calling function cause have context of window?
when execute
a.b();
then a
context of execution of b
(this
within b
) unless b
bound function.
if don't have a
, if have
b();
then it's same as
window.b();
so window
context of execution of b
.
note that
a.b();
is same as
b.call(a);
and
b();
is same as
b.call(); // phone call replaces first argument global object if it's null or undefined
if want bind context, can (on modern browsers)
var func = john.says.bind(john); func();
or (more classically) utilize closure :
var func = function(){john.says()}; func();
javascript
No comments:
Post a Comment