I've been trying to wrap my head around how javascript functions and scope work, and it just doesn't make sense to me. Can someone please explain why the following code outputs: 'animal says meow' instead of 'kitty says meow'?
(function($, exports){
var animal = function(){};
exports.Animal = animal;
})(jQuery, window);
(function($, Animal){
var kitty = new Animal;
kitty.sayHi = function(){
console.log(this);
console.log('says meow');
}
$($.proxy(function(){
$('#js_test').click($.proxy(kitty.sayHi, kitty));
}, kitty))
})(jQuery, Animal);
UPDATE
@FunkyFresh pointed out in the comments that console.log calls toString when it's passed an object, which by default returns the object's type (animal). When I update the above code with
animal.prototype.name = 'Mammal';
in the top block of code, and
kitty.name = 'Zax';
in the bottom, the console outputs 'Zax says meow', which seems about right.
An anonymous function is a function that was declared without any named identifier to refer to it. As such, an anonymous function is usually not accessible after its initial creation. Normal function definition: function hello() { alert('Hello world'); } hello();
proxy() Method in jQuery accepts an existing function and returns a new one with a particular context. Generally, it is used for attaching events to an element where the context is pointing back to a different object. Syntax: $(selector).
Anonymous functions, also known as closures , allow the creation of functions which have no specified name. They are most useful as the value of callable parameters, but they have many other uses. Anonymous functions are implemented using the Closure class.
The advantage of an anonymous function is that it does not have to be stored in a separate file. This can greatly simplify programs, as often calculations are very simple and the use of anonymous functions reduces the number of code files necessary for a program.
(function($) {})(jQuery)
in this code (function($){}) declares the function. Then (jQuery) imediately calls the function passing in the jQuery object.
so the first block of code passes in jQuery and the window object. Animal is added to the window object, which is the global scope.
in the second block a click event is added to an element and kitty.sayHi is passed in as the event handler. However if the event handler was not proxied then the this keyword in the eventhandler would return the element that has triggered the event. So by using the proxy the scope of the eventhandler becomes kitty.
I hope that is correct, this is new to me also.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With